Codice del bot (in Python)
Jump to navigation
Jump to search
Ecco il codice del bot:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
"""
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
# import random
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
votes={}
def vote(bot, update):
global votes
vote = update.message.text
user = update.message.chat_id
if vote[:5] == '/vote': vote = vote[5:]
if vote[:1] == ' ': vote = vote[1:]
vote = vote.lower()
if user in votes:
update.message.reply_text('vote changed to: '+ vote);
else:
update.message.reply_text('got your vote: '+ vote);
votes[user] = vote
def count(bot, update):
global votes
table = {}
for v in votes:
vote = votes[v]
if vote in table:
table[vote] += 1
else:
table[vote] = 1
if table:
print "Count results:"
for v in sorted(table, key=table.get, reverse=True):
print '[{}]: {}'.format(v, table[v])
votes = {}
def start(bot, update):
update.message.reply_text('Welcome to so_cs_unibot!')
def help(bot, update):
update.message.reply_text(
"""
This is so_cs_unibot!
/vote file your vote
/count vote counting
"""
)
def echo(bot, update):
"""Echo the user message."""
print update.message.text
## update.message.reply_text(update.message.text)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("vote", vote))
dp.add_handler(CommandHandler("count", count))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()