def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("166865409:AAGSAEVXHyP1NlQaDOj65z4F9OgX5sarpGg") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("boz", startHandler) dp.addTelegramCommandHandler("muto", stopHandler) dp.addTelegramCommandHandler("help", helpHandler) # on noncommand i.e message - send a proper message on Telegram dp.addTelegramMessageHandler(messageHandler) # log all errors dp.addErrorHandler(errorHandler) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("123456789:ABCDEFGHIJKLM") job_queue = updater.job_queue job_queue.put(track_items, 60, next_t=0) #job_queue.put(publish_new_offers, 60, next_t=0) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help_info) dp.addTelegramCommandHandler("add", add_item) dp.addTelegramCommandHandler("list", list_items) dp.addTelegramCommandHandler("readd", readd_items) dp.addTelegramCommandHandler("addme", add_user) dp.addTelegramCommandHandler("del", del_item) dp.addTelegramCommandHandler("canal", canal) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(settings.TG_API_KEY) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("on", cmd_on) dp.addTelegramCommandHandler("off", cmd_off) dp.addTelegramCommandHandler("check", cmd_check) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(token) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("start", home) dp.addTelegramCommandHandler("home", home) dp.addTelegramCommandHandler("price", price) dp.addTelegramCommandHandler("register", register) dp.addTelegramCommandHandler("balances", balances) dp.addTelegramCommandHandler("transactions", transactions) dp.addTelegramCommandHandler("trades", trades) dp.addTelegramCommandHandler("tickers", tickers) dp.addTelegramCommandHandler("discounts", discounts) dp.addTelegramCommandHandler("delete_keys", deleteKeys) dp.addTelegramCommandHandler("bitcoin_data", bitcoinData) dp.addTelegramCommandHandler("orders", orders) for fund in FUNDS: dp.addTelegramCommandHandler(('tr_' + fund), fundTrades) dp.addTelegramCommandHandler(('tick_' + fund), ticker) dp.addTelegramCommandHandler(('ord_'+fund), fundOrders) for currency in CURRENCIES: dp.addTelegramCommandHandler(('disc_' + currency), currDiscount) dp.addTelegramMessageHandler(signup) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): global logger # load the logging configuration real_path = os.path.dirname(os.path.realpath(__file__)) logging.config.fileConfig(real_path + '/logging.ini') logger = logging.getLogger(__name__) # Get the dispatcher to register handlers updater = Updater(token="TOKEN") dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("roll", Dice.roll) # log all errors dp.addErrorHandler(error) logger.info('Starting new bot') roll() # Start the Bot updater.start_polling() # Block until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(token) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("help", home) dp.addTelegramCommandHandler("start", home) dp.addTelegramCommandHandler("home", home) dp.addTelegramCommandHandler("botinfo", botinfo) dp.addTelegramCommandHandler("mensa", mensa) dp.addTelegramCommandHandler("aulastudio", aulastudio) dp.addTelegramCommandHandler("biblioteca", biblioteca) for command in commands: dp.addTelegramCommandHandler(command, replier) dp.addTelegramMessageHandler(position) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): """Main program""" # Create the EventHandler and pass it your bot's token. updater = Updater(token='KEY') # Get the dispatcher to register handlers dispatcher = updater.dispatcher # on different commands - answer in Telegram dispatcher.addTelegramCommandHandler('start', start) dispatcher.addTelegramCommandHandler('nuevavotacion', newpoll) dispatcher.addTelegramCommandHandler('respuesta', response) dispatcher.addTelegramCommandHandler('iniciovotacion', initpoll) dispatcher.addTelegramCommandHandler('finvotacion', endpoll) dispatcher.addUnknownTelegramCommandHandler(unknown) # on noncommand i.e message dispatcher.addTelegramMessageHandler(receiver) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): """Defining the main function""" global JOB_QUEUE news.create_news_json() utils.load_subscribers_json() config = utils.get_configuration() token = config.get('API-KEYS', 'TelegramBot') debug = config.getboolean('UTILS', 'Debug') logger = utils.get_logger(debug) updater = Updater(token) JOB_QUEUE = updater.job_queue notify_news(updater.bot) dispatcher = updater.dispatcher dispatcher.addTelegramCommandHandler("start", start_command) dispatcher.addTelegramCommandHandler("help", help_command) dispatcher.addTelegramCommandHandler("news", news.news_command) dispatcher.addTelegramCommandHandler("newson", newson_command) dispatcher.addTelegramCommandHandler("newsoff", newsoff_command) dispatcher.addTelegramCommandHandler("prof", other_commands.prof_command) dispatcher.addTelegramCommandHandler("segreteria", other_commands.student_office_command) dispatcher.addTelegramCommandHandler("mensa", other_commands.canteen_command) dispatcher.addTelegramCommandHandler("adsu", other_commands.adsu_command) # For Testing only dispatcher.addTelegramCommandHandler("commands_keyboard", commands_keyboard) logger.info('Bot started') updater.start_polling() updater.idle()
def main(): """Main program""" # Create the EventHandler and pass it your bot's token. updater = Updater(token='KEY') # Get the dispatcher to register handlers dispatcher = updater.dispatcher # on different commands - answer in Telegram dispatcher.addTelegramCommandHandler('start', start) dispatcher.addTelegramCommandHandler('nuevavotacion', newpoll) dispatcher.addTelegramCommandHandler('respuesta', response) dispatcher.addTelegramCommandHandler('iniciovotacion', initpoll) dispatcher.addTelegramCommandHandler('finvotacion', endpoll) dispatcher.addUnknownTelegramCommandHandler(unknown) # on noncommand i.e message dispatcher.addTelegramMessageHandler(receiver) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(BOTKEY) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram for cmd in ['up', 'down', 'refresh', 'status']: dp.addTelegramCommandHandler(cmd, ssrs) for cmd in ['newbot', 'forcenewbot']: dp.addTelegramCommandHandler(cmd, newbot) for cmd in [1]: dp.addTelegramCommandHandler('updatebot', updatebot) dp.addTelegramCommandHandler('rmbot', rmbot) dp.addTelegramCommandHandler('listbots', listbots) dp.addTelegramCommandHandler("start", help) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(private_conf.tokenid) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("subscribe_op", subscribe_op) dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("leeop",leeop) #run One Piece manga checker run_op(updater.bot) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): cnf = loadConfig() TOKEN = cnf["token"] games = cnf["games"] print "games in: ", games # Create the EventHandler and pass it your bot's token. updater = Updater(TOKEN) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("list_games", ls_closure(cnf)) dp.addTelegramCommandHandler("start_game", start_closure(cnf)) dp.addTelegramCommandHandler("update", update_cmd) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(process_message_closure(cnf)) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
class IngressoRapidoBot(object): # Mapa de comandos -> funções de tratamento commands = { 'start': start_handler, 'eventosnodia': events_on_handler, 'eventosem': events_at_handler, 'eventosdotipo': events_type_handler, 'busca': search_handler, 'eventosnoperiodo': events_between_handler, 'mais': more_handler, 'shows': shows_handler, 'festas': parties_handler, 'cinema': cinema_handler, 'esportes': sports_handler, 'teatro': theater_handler } def __init__(self, token): self.updater = Updater(token=token) dispatcher = self.updater.dispatcher for cmd, cmd_handler in self.commands.iteritems(): dispatcher.addTelegramCommandHandler(cmd, cmd_handler) def run(self): self.updater.start_polling() self.updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("135342801:AAFaninNSzDkYU8UzonHeOhcu5fVaPlCC7Y") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() runloop() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. #updater = Updater(settings.APITOKEN) updater = Updater(APITOKEN) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("randomvideo", randomvideo) dp.addTelegramCommandHandler("random", random) dp.addTelegramCommandHandler("caso", caso) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("135342801:AAFaninNSzDkYU8UzonHeOhcu5fVaPlCC7Y") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() runloop() # Run the bot until the you presses 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()
def main(): global logger # load the logging configuration real_path = os.path.dirname(os.path.realpath(__file__)) logging.config.fileConfig(real_path + '/logging.ini') logger = logging.getLogger(__name__) # Get the dispatcher to register handlers updater = Updater(token="TOKEN") dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("roll", Dice.roll) # log all errors dp.addErrorHandler(error) logger.info('Starting new bot') roll() # Start the Bot updater.start_polling() # Block until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(token) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("start", home) dp.addTelegramCommandHandler("home", home) dp.addTelegramCommandHandler("price", price) dp.addTelegramCommandHandler("register", register) dp.addTelegramCommandHandler("balances", balances) dp.addTelegramCommandHandler("transactions", transactions) dp.addTelegramCommandHandler("trades", trades) dp.addTelegramCommandHandler("tickers", tickers) dp.addTelegramCommandHandler("discounts", discounts) dp.addTelegramCommandHandler("delete_keys", deleteKeys) dp.addTelegramCommandHandler("bitcoin_data", bitcoinData) dp.addTelegramCommandHandler("orders", orders) for fund in FUNDS: dp.addTelegramCommandHandler(('tr_' + fund), fundTrades) dp.addTelegramCommandHandler(('tick_' + fund), ticker) dp.addTelegramCommandHandler(('ord_' + fund), fundOrders) for currency in CURRENCIES: dp.addTelegramCommandHandler(('disc_' + currency), currDiscount) dp.addTelegramMessageHandler(signup) dp.addErrorHandler(error) updater.start_polling() updater.idle()
class IngressoRapidoBot(object): # Mapa de comandos -> funções de tratamento commands = { 'start': start_handler, 'eventosnodia': events_on_handler, 'eventosem': events_at_handler, 'eventosdotipo': events_type_handler, 'busca': search_handler, 'eventosnoperiodo': events_between_handler, 'mais': more_handler, 'shows': shows_handler, 'festas': parties_handler, 'cinema': cinema_handler, 'esportes': sports_handler, 'teatro': theater_handler } def __init__(self, token): self.updater = Updater(token=token) dispatcher = self.updater.dispatcher for cmd, cmd_handler in self.commands.iteritems(): dispatcher.addTelegramCommandHandler(cmd, cmd_handler) def run(self): self.updater.start_polling() self.updater.idle()
def main(): thread.start_new_thread(checkFlood, (2, )) updater = Updater(botID) dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("google", google) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): thread.start_new_thread(checkFlood, (2,)) updater = Updater(botID) dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("google", google) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): mybot = Updater("699053794:AAH8KEIug-7IZXTSlUOMQGfFEq_oyrVPQtk", request_kwargs=PROXY) dp = mybot.dispatcher dp.add_handler(CommandHandler("start", greet_user)) dp.add_handler(CommandHandler("planet", planet_take)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) print('*'*10) mybot.start_polling() mybot.idle() print('*' * 10)
def main(): # parse argument from command line parser = argparse.ArgumentParser( description='Personal Telegram Bot' ) parser.add_argument( '-l', action='store_true', help='If set write log in stdout.' ) args = parser.parse_args() global logger if args.l: logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # get the updater updater = Updater(getToken()) # Get the dispatcher to register handlers dp = updater.dispatcher # Set different commands that marvin must respond # Fill commands hash map with # - key: the name of command that marvin must respond # - value: a tuple as (handler function, description) commands['start'] = (start, "start chatting with Marvin") commands['help'] = (help, "list the possible commands") commands['hi_marvin'] = (sayHello, "greeting Marvin") commands['introduce'] = (start, "Marvin introduce itself") commands['test_args'] = (testArgs, "test command") for k, v in commands.items(): dp.addTelegramCommandHandler(k, v[0]) # Handle the unrecognized command dp.addUnknownTelegramCommandHandler(unrecognizedCommand) # Implement this if you want that marvin respond to messages # that not start with / # dp.addTelegramMessageHandler() # If errors happens, call the function given dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): updater=Updater("136820376:AAFgZ66FHblXImb0m-QyHj5i4gZAQ-5sN_c") dp=updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramMessageHandler(startReturnThread) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): updater = Updater(token='TOKEN') dp = updater.dispatcher dp.addTelegramCommandHandler('start', start) dp.addTelegramCommandHandler('help', help) dp.addTelegramCommandHandler('log', log) dp.addTelegramCommandHandler('test', test) dp.addTelegramMessageHandler(echo) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): updater = Updater(TOKEN) # Get the dispatcher to register handlers dp = updater.dispatcher # Add handlers for Telegram commands for (name, f) in bot_functions.items(): dp.addTelegramCommandHandler(name, f) dp.addTelegramMessageHandler(bank_name_answer_handler) updater.start_polling() updater.idle()
def main(): """Add command handlers specified earlier and start the bot.""" updater = Updater(TOKEN) dispatcher = updater.dispatcher dispatcher.addTelegramCommandHandler("start", bot_start) dispatcher.addTelegramCommandHandler("online", bot_online) dispatcher.addTelegramCommandHandler("help", bot_help) dispatcher.addErrorHandler(bot_error) updater.start_polling() updater.idle()
def run_bot(): updater = Updater(BOT_TOCKEN) updater.dispatcher.addErrorHandler(on_error) updater.dispatcher.addTelegramCommandHandler("start", on_start) updater.dispatcher.addTelegramCommandHandler("ls", on_ls) updater.dispatcher.addTelegramCommandHandler("cd", on_cd) updater.dispatcher.addTelegramCommandHandler("get", on_get) updater.dispatcher.addTelegramCommandHandler("cat", on_cat) updater.dispatcher.addTelegramCommandHandler("pwd", on_pwd) updater.dispatcher.addTelegramCommandHandler("history", on_history) updater.dispatcher.addTelegramMessageHandler(on_message) updater.start_polling() updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("221791426:AAGRMjmhyhGehCpT0SvkYUfLBlvLtpMpB_M") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("ТОКЕН") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() updater.idle()
def main(): updater = Updater(token='TOKEN') dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramMessageHandler(echo) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): global job_queue token = '142603543:AAGjbFCNsRAsnNbueaF19UuGrjhEgvDqbpY' updater = Updater(token) job_queue = updater.job_queue dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("start_timer", start_timer) dp.addTelegramCommandHandler("cancel", cancel) dp.addTelegramMessageHandler(any_message) updater.start_polling() updater.idle()
def main(): global job_queue updater = Updater(token='145193673:AAGX8s8NQFqJTbbi1ZAEuhjVxstToboziw8') job_queue = updater.job_queue dp = updater.dispatcher dp.addTelegramCommandHandler('start', start) dp.addTelegramCommandHandler('stop', stop) dp.addErrorHandler(error) updater.start_polling() updater.idle()
def main(): updater = Updater("KEY") dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("gerrit", gerrit) dp.addTelegramCommandHandler("turingtest", turingtest) dp.addTelegramCommandHandler("halay", halay) dp.addTelegramMessageHandler(echo) dp.addErrorHandler(error) updater.start_polling(timeout=5) updater.idle()
def main(): updater = Updater("KEY") dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramCommandHandler("gerrit", gerrit) dp.addTelegramCommandHandler("turingtest", turingtest) dp.addTelegramCommandHandler("halay", halay) dp.addTelegramCommandHandler("icselhalay", icselhalay) dp.addTelegramCommandHandler("turku", turku) dp.addTelegramMessageHandler(echo) dp.addErrorHandler(error) updater.start_polling(timeout=5) updater.idle()
def main(): global job_queue updater = Updater(TELEGRAM_TOKEN) dp = updater.dispatcher dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) dp.addTelegramMessageHandler(echo) dp.addErrorHandler(error) updater.job_queue.put(jobJoke, 28800, repeat=True) updater.start_polling() updater.idle()
def bot_main(bot_token=""): # Create the EventHandler and pass it your bot's token. updater = Updater(bot_token) common.bot = updater.bot # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("subscribe", subscribe) dp.addTelegramCommandHandler("unsubscribe", unsubscribe) # Start the Bot updater.start_polling(timeout=5) # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def main(): global CLIENT # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN_HERE") # Set URL to Dublin Bus RTPI url = 'http://rtpi.dublinbus.ie/DublinBusRTPIService.asmx?wsdl' # Import the correct XML Schema and namespace imp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd') imp.filter.add('http://dublinbus.ie/') d = ImportDoctor(imp) # Setup the global client with the import doctor and url try: CLIENT = Client(url, doctor=d) print "Suds Client Connected" except: print "Client connection error" # UTF-8: http://stackoverflow.com/a/17628350 reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(message) # on error - print error to stdout dp.addErrorHandler(error) # Start the Bot updater.start_polling(timeout=5) # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def main(): bot_dir = os.path.dirname(os.path.realpath(__file__))[:-3] plugin_dir = bot_dir+'plugins/' # Get bot auth token. token = '' with open(bot_dir+'etc/token', 'r') as token_f: token = token_f.readline().rstrip() token_f.close() # Creating the updater and the dispatcher. updater = Updater(token) dp = updater.dispatcher # Import all modules. sys.path.append(bot_dir) import plugins # Parse all the files for the function names, I'm not really a fan of this, but it works. for module in os.listdir(os.path.dirname(plugin_dir)): if module == '__init__.py' or module[-3:] != '.py': continue with open(plugin_dir+module, 'r') as f: for line in f: if line[:3] != 'def': continue command = line[4:].split('(', 1)[0] mod = 'plugins.'+module[:-3] # For debug purposes print the loaded functions and the module they belong. print command+' '+ mod var = sys.modules[mod] handler = getattr(var, command) # Add all functions from all modules to the dispatcher. dp.addTelegramCommandHandler(command, handler) f.close() del module updater.start_polling() updater.idle()
def main(): global CLIENT # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN_HERE") # Set URL to Dublin Bus RTPI url = "http://rtpi.dublinbus.ie/DublinBusRTPIService.asmx?wsdl" # Import the correct XML Schema and namespace imp = Import("http://www.w3.org/2001/XMLSchema", location="http://www.w3.org/2001/XMLSchema.xsd") imp.filter.add("http://dublinbus.ie/") d = ImportDoctor(imp) # Setup the global client with the import doctor and url try: CLIENT = Client(url, doctor=d) print "Suds Client Connected" except: print "Client connection error" # UTF-8: http://stackoverflow.com/a/17628350 reload(sys) # Reload does the trick! sys.setdefaultencoding("UTF8") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(message) # on error - print error to stdout dp.addErrorHandler(error) # Start the Bot updater.start_polling(timeout=5) # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("128116768:AAFsiMmSV7KjiN8xIidv7eX8TNgbnJ4zMLA") jobs = updater.job_queue jobs.put(update, 1, prevent_autostart=False) # Get the dispatcher to register handlers dp = updater.dispatcher dp.addTelegramCommandHandler('status',statusOfPlant) dp.addTelegramCommandHandler('register',register) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): token = os.environ["TOKEN"] updater = Updater(token) dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("diana", diana) # on noncommand i.e message - echo the message on Telegram # dp.addTelegramMessageHandler(echo) # on error - print error to stdout dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def main(): token = os.environ["TOKEN"] updater = Updater(token) dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("diana", diana) # on noncommand i.e message - echo the message on Telegram # dp.addTelegramMessageHandler(echo) # on error - print error to stdout dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def main(): updater = Updater("153154827:AAH3_zfoVMsvUEYXpQ4BgnTUxlEFGp9Hspc") ud = updater.dispatcher ud.addTelegramCommandHandler("start", help) ud.addTelegramCommandHandler("setRegion", setRegion) ud.addTelegramCommandHandler(set_region) # Hack ud.addTelegramCommandHandler("setLevel", setSchool_level) ud.addTelegramCommandHandler(set_level) # Hack ud.addTelegramCommandHandler("setSchool", setSchool) ud.addTelegramCommandHandler(set_school) # Hack ud.addTelegramCommandHandler("info", info) ud.addTelegramCommandHandler("lunch", lunch) ud.addTelegramCommandHandler("breakfast", breakfast) ud.addTelegramCommandHandler("dinner", dinner) # log all errors ud.addErrorHandler(error) # Start the Bot updater.start_polling() updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(config.token) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("add", add) dp.addTelegramCommandHandler("del", delete) dp.addTelegramCommandHandler("upd", upd) dp.addTelegramCommandHandler("all", all) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): #create event handler updater = Updater(token = authInst.getToken()) dispatcher = updater.dispatcher # register handlers dispatcher.addTelegramCommandHandler("start", start) dispatcher.addTelegramCommandHandler("help", help) # register Handlers from service modules and registered in configuration.json utilsInst.addCommandHandlerFromModules(dispatcher) # on noncommand dispatcher.addUnknownTelegramCommandHandler(unknown) dispatcher.addTelegramMessageHandler(echo) # Error handler dispatcher.addErrorHandler(error) #start BOT updater.start_polling(timeout=5) updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN") # Get the dispatcher to register handlers dp = updater.dispatcher dp.addConversationHandler('start', Echo) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): """Defining the main function""" global JOB_QUEUE news.create_news_json() utils.load_subscribers_json() config = utils.get_configuration() token = config.get('API-KEYS', 'TelegramBot') debug = config.getboolean('UTILS', 'Debug') logger = utils.get_logger(debug) updater = Updater(token) JOB_QUEUE = updater.job_queue notify_news(updater.bot) dispatcher = updater.dispatcher dispatcher.addTelegramCommandHandler("start", start_command) dispatcher.addTelegramCommandHandler("help", help_command) dispatcher.addTelegramCommandHandler("news", news.news_command) dispatcher.addTelegramCommandHandler("newson", newson_command) dispatcher.addTelegramCommandHandler("newsoff", newsoff_command) dispatcher.addTelegramCommandHandler("prof", other_commands.prof_command) dispatcher.addTelegramCommandHandler("segreteria", other_commands.student_office_command) dispatcher.addTelegramCommandHandler("mensa", other_commands.canteen_command) dispatcher.addTelegramCommandHandler("adsu", other_commands.adsu_command) # For Testing only dispatcher.addTelegramCommandHandler("commands_keyboard", commands_keyboard) logger.info('Bot started') updater.start_polling() updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # on error - print error to stdout dp.addErrorHandler(error) # Start the Bot updater.start_polling(timeout=5) # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def run(self): # Create the EventHandler and pass it your bot's token. updater = Updater("194949588:AAETiWnXkKaOipiu2jaKHWmcTWnPfHXLXf0") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("help", self.help) dp.addTelegramCommandHandler("talk", self.talk) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(self.echo) # log all errors dp.addErrorHandler(self.error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): global job_queue updater = Updater("TOKEN") job_queue = updater.job_queue # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", start) dp.addTelegramCommandHandler("set", set) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Block until the you presses 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()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(config.get('TELEGRAM_TOKEN')) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler('start', start) dp.addTelegramCommandHandler('help', help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(echo) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses 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()
def main(): # Create the Updater and pass it your bot's token. updater = Updater("TOKEN") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramInlineHandler(inlinequery) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() # Block until the user presses 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 user_type == "user": bot.sendMessage(update.message.chat_id, "User: [%s]" % update.message.from_user.username) return if user_type == "su": bot.sendMessage(update.message.chat_id, "Super user: [%s]" % update.message.from_user.username) return def comando_help(bot, update): help_text = ("/otp Genera una one time password\n" "/userlist Lista utenti\n" "/userdel Cancella tutti gli utenti\n") user_type = check.user(bot, update) if user_type != "none": bot.sendMessage(update.message.chat_id, help_text) return updater = Updater(token='145378027:AAGKpq8P6hggT8oAqoWJ6Y_qcXoXJ2Zn96w') dispatcher = updater.dispatcher dispatcher.addTelegramMessageHandler(messaggi_in_arrivo) dispatcher.addTelegramCommandHandler("start", comando_start) dispatcher.addTelegramCommandHandler("help", comando_help) check.addTanzoCheckCommandHandler(dispatcher) updater.start_polling() updater.idle()
class Bot: def __init__(self, token, vk_client_id): self.poller = Poller() self.updater = Updater(token=token) self.vk = Vk(vk_client_id) self.clients = Client.all_from_db() self.reg_actions() self.restore() def run(self): self.poller.async_run(self.on_update) self.updater.start_polling() self.updater.idle() self.poller.stop() self.persist() db.close() def persist(self): for _, client in self.clients.items(): client.persist() def restore(self): for _, client in self.clients.items(): self.add_poll_server(client) def reg_actions(self): dispatcher = self.updater.dispatcher dispatcher.addTelegramCommandHandler('start', self.start) dispatcher.addTelegramCommandHandler('whoami', self.whoami) dispatcher.addTelegramCommandHandler('pick', self.pick) dispatcher.addTelegramCommandHandler('unpick', self.unpick) dispatcher.addTelegramCommandHandler('details', self.details) dispatcher.addErrorHandler(self.error) dispatcher.addUnknownTelegramCommandHandler(self.unknown) dispatcher.addTelegramMessageHandler(self.on_message) def start(self, bot, update): chat_id = update.message.chat_id auth_url = self.vk.get_auth_url() # Send first info messages bot.sendMessage(chat_id=chat_id, text=message.WELCOME(auth_url), reply_markup=ReplyKeyboardHide()) bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN) # Create new client client = Client(next_action=action.ACCESS_TOKEN, chat_id=chat_id) self.clients[chat_id] = client client.persist() def whoami(self, bot, update): chat_id = update.message.chat_id if not chat_id in self.clients: return client = self.clients[chat_id] bot.sendMessage(chat_id=chat_id, text=message.WHOAMI(client.vk_user.get_name()), reply_markup=Bot.keyboard(client.keyboard_markup())) def pick(self, bot, update): chat_id = update.message.chat_id if not chat_id in self.clients: self.start(bot, update) return client = self.clients[chat_id] client.seen_now() recepient = update.message.text[6:] client.expect_message_to(recepient) bot.sendMessage(chat_id=chat_id, text=message.TYPE_MESSAGE(recepient), parse_mode=ParseMode.MARKDOWN, reply_markup=Bot.keyboard(client.keyboard_markup())) def unpick(self, bot, update): chat_id = update.message.chat_id if not chat_id in self.clients: self.start(bot, update) return client = self.clients[chat_id] client.next_action = action.NOTHING client.persist() bot.sendMessage(chat_id=chat_id, text=message.UNPICK(client.next_recepient.get_name()), parse_mode=ParseMode.MARKDOWN, reply_markup=Bot.keyboard(client.keyboard_markup())) client.next_recepient = None def details(self, bot, update): chat_id = update.message.chat_id if not chat_id in self.clients: self.start(bot, update) return client = self.clients[chat_id] client.seen_now() user = client.next_recepient if user == None: bot.sendMessage(chat_id=chat_id, text=message.FIRST_PICK_USER, reply_markup=Bot.keyboard( client.keyboard_markup())) return if user.photo != None: bot.sendPhoto(chat_id=chat_id, photo=user.photo) bot.sendMessage(chat_id=chat_id, text=message.USER_NAME(user.get_name()), parse_mode=ParseMode.MARKDOWN, reply_markup=Bot.keyboard(client.keyboard_markup())) participants = user.participants() if participants != None: bot.sendMessage(chat_id=chat_id, text=message.PARTICIPANTS(participants), parse_mode=ParseMode.MARKDOWN, reply_markup=Bot.keyboard( client.keyboard_markup())) def error(self, bot, update, error): logger.warn('Update "%s" caused error "%s"' % (update, error)) def on_message(self, bot, update): chat_id = update.message.chat_id if not chat_id in self.clients: return self.start(bot, update) client = self.clients[chat_id] client.seen_now() if client.next_action == action.ACCESS_TOKEN: return self.on_token_message(bot, update, client) elif client.next_action == action.MESSAGE: return self.on_typed_message(bot, update, client) self.echo(update.message.chat_id) def on_token_message(self, bot, update, client): parseresult = urlparse(update.message.text) if parseresult.scheme == 'https': parseparams = parse_qs(parseresult.fragment) access_token = parseparams.get('access_token')[0] client.load_vk_user(access_token) else: client.load_vk_user(update.message.text) name = client.vk_user.get_name() client.next_action = action.NOTHING self.add_poll_server(client) bot.sendMessage(chat_id=update.message.chat_id, text=message.TOKEN_SAVED(name), reply_markup=Bot.keyboard(client.keyboard_markup())) def on_typed_message(self, bot, update, client): client.send_message(update.message.text) @run_async def add_poll_server(self, client): if client.vk_token != None: self.poller.add(client) def echo(self, chat_id): self.updater.bot.sendMessage(chat_id=chat_id, text=message.ECHO) def unknown(self, bot, update): bot.sendMessage(chat_id=update.message.chat_id, text=message.UNKNOWN) @staticmethod def keyboard(keyboard_markup): return ReplyKeyboardMarkup(keyboard_markup, selective=True, resize_keyboard=True) def on_update(self, updates, client): for update in updates: self.process_update(update, client) def process_update(self, update, client): if len(update) == 0: return if update[0] == 4: # When new message received self.receive_vk_message(update, client) def receive_vk_message(self, update, client): flags = update[2] from_id = update[3] text = update[6] attachments = update[7] if flags & 2 == 2: # Skip when message is outgoing return from_name = '' if from_id & 2000000000 == 2000000000: # Message came from chat chat_id = from_id - 2000000000 chat = Vk_chat.fetch(client.vk_token, chat_id) from_name = chat.name_from(attachments['from']) client.add_interaction_with(chat) else: user = Vk_user.fetch_user(client.vk_token, from_id) from_name = user.get_name() client.add_interaction_with(user) self.updater.bot.sendMessage(chat_id=client.chat_id, text=message.NEW_MESSAGE(from_name, text), reply_markup=Bot.keyboard( client.keyboard_markup()), parse_mode=ParseMode.MARKDOWN) client.persist()
class UpdaterTest(BaseTest, unittest.TestCase): """ This object represents Tests for Updater, Dispatcher, WebhookServer and WebhookHandler """ def setUp(self): self.updater = None self.received_message = None self.message_count = 0 self.lock = Lock() def _setup_updater(self, *args, **kwargs): bot = MockBot(*args, **kwargs) self.updater = Updater(workers=2, bot=bot) def tearDown(self): if self.updater is not None: self.updater.stop() def reset(self): self.message_count = 0 self.received_message = None def telegramHandlerTest(self, bot, update): self.received_message = update.message.text self.message_count += 1 def telegramInlineHandlerTest(self, bot, update): self.received_message = (update.inline_query, update.chosen_inline_result) self.message_count += 1 @run_async def asyncHandlerTest(self, bot, update, **kwargs): sleep(1) with self.lock: self.received_message = update.message.text self.message_count += 1 def stringHandlerTest(self, bot, update): self.received_message = update self.message_count += 1 def regexGroupHandlerTest(self, bot, update, groups=None, groupdict=None): self.received_message = (groups, groupdict) self.message_count += 1 def additionalArgsTest(self, bot, update, update_queue, args): self.received_message = update self.message_count += 1 if args[0] == 'resend': update_queue.put('/test5 noresend') elif args[0] == 'noresend': pass def contextTest(self, bot, update, context): self.received_message = update self.message_count += 1 self.context = context @run_async def asyncAdditionalHandlerTest(self, bot, update, update_queue=None, **kwargs): sleep(1) with self.lock: if update_queue is not None: self.received_message = update.message.text self.message_count += 1 def errorRaisingHandlerTest(self, bot, update): raise TelegramError(update) def errorHandlerTest(self, bot, update, error): self.received_message = error.message self.message_count += 1 def test_addRemoveTelegramMessageHandler(self): self._setup_updater('Test') d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, 'Test') # Remove handler d.removeTelegramMessageHandler(self.telegramHandlerTest) self.reset() self.updater.bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addTelegramMessageHandlerMultipleMessages(self): self._setup_updater('Multiple', 100) self.updater.dispatcher.addTelegramMessageHandler( self.telegramHandlerTest) self.updater.start_polling(0.0) sleep(2) self.assertEqual(self.received_message, 'Multiple') self.assertEqual(self.message_count, 100) def test_addRemoveTelegramRegexHandler(self): self._setup_updater('Test2') d = self.updater.dispatcher regobj = re.compile('Te.*') self.updater.dispatcher.addTelegramRegexHandler( regobj, self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, 'Test2') # Remove handler d.removeTelegramRegexHandler(regobj, self.telegramHandlerTest) self.reset() self.updater.bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveTelegramCommandHandler(self): self._setup_updater('/test') d = self.updater.dispatcher self.updater.dispatcher.addTelegramCommandHandler( 'test', self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, '/test') # Remove handler d.removeTelegramCommandHandler('test', self.telegramHandlerTest) self.reset() self.updater.bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveUnknownTelegramCommandHandler(self): self._setup_updater('/test2') d = self.updater.dispatcher self.updater.dispatcher.addUnknownTelegramCommandHandler( self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, '/test2') # Remove handler d.removeUnknownTelegramCommandHandler(self.telegramHandlerTest) self.reset() self.updater.bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveStringRegexHandler(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addStringRegexHandler('Te.*', self.stringHandlerTest) queue = self.updater.start_polling(0.01) queue.put('Test3') sleep(.1) self.assertEqual(self.received_message, 'Test3') # Remove handler d.removeStringRegexHandler('Te.*', self.stringHandlerTest) self.reset() queue.put('Test3') sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveStringCommandHandler(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addStringCommandHandler('test3', self.stringHandlerTest) queue = self.updater.start_polling(0.01) queue.put('/test3') sleep(.1) self.assertEqual(self.received_message, '/test3') # Remove handler d.removeStringCommandHandler('test3', self.stringHandlerTest) self.reset() queue.put('/test3') sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveUnknownStringCommandHandler(self): self._setup_updater('/test') d = self.updater.dispatcher d.addUnknownStringCommandHandler(self.stringHandlerTest) queue = self.updater.start_polling(0.01) queue.put('/test4') sleep(.1) self.assertEqual(self.received_message, '/test4') # Remove handler d.removeUnknownStringCommandHandler(self.stringHandlerTest) self.reset() self.updater.bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveErrorHandler(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addErrorHandler(self.errorHandlerTest) queue = self.updater.start_polling(0.01) error = TelegramError("Unauthorized.") queue.put(error) sleep(.1) self.assertEqual(self.received_message, "Unauthorized.") # Remove handler d.removeErrorHandler(self.errorHandlerTest) self.reset() queue.put(error) sleep(.1) self.assertTrue(None is self.received_message) def test_errorInHandler(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addStringRegexHandler('.*', self.errorRaisingHandlerTest) self.updater.dispatcher.addErrorHandler(self.errorHandlerTest) queue = self.updater.start_polling(0.01) queue.put('Test Error 1') sleep(.1) self.assertEqual(self.received_message, 'Test Error 1') def test_cleanBeforeStart(self): self._setup_updater('') d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) self.updater.start_polling(0.01, clean=True) sleep(.1) self.assertEqual(self.message_count, 0) self.assertIsNone(self.received_message) def test_errorOnGetUpdates(self): self._setup_updater('', raise_error=True) d = self.updater.dispatcher d.addErrorHandler(self.errorHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, "Test Error 2") def test_addRemoveTypeHandler(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addTypeHandler(dict, self.stringHandlerTest) queue = self.updater.start_polling(0.01) payload = {"Test": 42} queue.put(payload) sleep(.1) self.assertEqual(self.received_message, payload) # Remove handler d.removeTypeHandler(dict, self.stringHandlerTest) self.reset() queue.put(payload) sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveInlineHandlerQuery(self): print('Testing add/removeInlineHandler') self._setup_updater('', messages=0) d = self.updater.dispatcher d.addTelegramInlineHandler(self.telegramInlineHandlerTest) queue = self.updater.start_polling(0.01) update = Update(update_id=0, inline_query="testquery") update2 = Update(update_id=0, chosen_inline_result="testresult") queue.put(update) sleep(.1) self.assertEqual(self.received_message[0], "testquery") queue.put(update2) sleep(.1) self.assertEqual(self.received_message[1], "testresult") # Remove handler d.removeTelegramInlineHandler(self.telegramInlineHandlerTest) self.reset() queue.put(update) sleep(.1) self.assertTrue(None is self.received_message) def test_runAsync(self): self._setup_updater('Test5', messages=2) d = self.updater.dispatcher d.addTelegramMessageHandler(self.asyncHandlerTest) self.updater.start_polling(0.01) sleep(1.2) self.assertEqual(self.received_message, 'Test5') self.assertEqual(self.message_count, 2) def test_additionalArgs(self): self._setup_updater('', messages=0) self.updater.dispatcher.addStringCommandHandler( 'test5', self.additionalArgsTest) queue = self.updater.start_polling(0.01) queue.put('/test5 resend') sleep(.1) self.assertEqual(self.received_message, '/test5 noresend') self.assertEqual(self.message_count, 2) def test_context(self): context = "context_data" self._setup_updater('', messages=0) self.updater.dispatcher.addStringCommandHandler( 'test_context', self.contextTest) queue = self.updater.start_polling(0.01) queue.put('/test_context', context=context) sleep(.5) self.assertEqual(self.received_message, '/test_context') self.assertEqual(self.message_count, 1) self.assertEqual(self.context, context) def test_regexGroupHandler(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addStringRegexHandler('^(This).*?(?P<testgroup>regex group).*', self.regexGroupHandlerTest) queue = self.updater.start_polling(0.01) queue.put('This is a test message for regex group matching.') sleep(.1) self.assertEqual(self.received_message, (('This', 'regex group'), { 'testgroup': 'regex group' })) def test_runAsyncWithAdditionalArgs(self): self._setup_updater('Test6', messages=2) d = self.updater.dispatcher d.addTelegramMessageHandler(self.asyncAdditionalHandlerTest) self.updater.start_polling(0.01) sleep(1.2) self.assertEqual(self.received_message, 'Test6') self.assertEqual(self.message_count, 2) def test_webhook(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port for travis self.updater.start_webhook(ip, port, url_path='TOKEN', cert='./tests/test_updater.py', key='./tests/test_updater.py') sleep(0.5) # SSL-Wrapping will fail, so we start the server without SSL Thread(target=self.updater.httpd.serve_forever).start() # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester"), datetime.now(), Chat(1, "group", title="Test Group")) message.text = "Webhook Test" update = Update(1) update.message = message self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN') sleep(1) self.assertEqual(self.received_message, 'Webhook Test') print("Test other webhook server functionalities...") response = self._send_webhook_msg(ip, port, None, 'webookhandler.py') self.assertEqual(b'', response.read()) self.assertEqual(200, response.code) response = self._send_webhook_msg(ip, port, None, 'webookhandler.py', get_method=lambda: 'HEAD') self.assertEqual(b'', response.read()) self.assertEqual(200, response.code) # Test multiple shutdown() calls self.updater.httpd.shutdown() self.updater.httpd.shutdown() self.assertTrue(True) def test_webhook_no_ssl(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port for travis self.updater.start_webhook(ip, port) sleep(0.5) # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester 2"), datetime.now(), Chat(1, 'group', title="Test Group 2")) message.text = "Webhook Test 2" update = Update(1) update.message = message self._send_webhook_msg(ip, port, update.to_json()) sleep(1) self.assertEqual(self.received_message, 'Webhook Test 2') def test_webhook_invalid_posts(self): self._setup_updater('', messages=0) ip = '127.0.0.1' port = randrange(1024, 49152) # select random port for travis thr = Thread(target=self.updater._start_webhook, args=(ip, port, '', None, None)) thr.start() sleep(0.5) try: with self.assertRaises(HTTPError) as ctx: self._send_webhook_msg(ip, port, '<root><bla>data</bla></root>', content_type='application/xml') self.assertEqual(ctx.exception.code, 403) with self.assertRaises(HTTPError) as ctx: self._send_webhook_msg(ip, port, 'dummy-payload', content_len=-2) self.assertEqual(ctx.exception.code, 403) # TODO: prevent urllib or the underlying from adding content-length # with self.assertRaises(HTTPError) as ctx: # self._send_webhook_msg(ip, port, 'dummy-payload', # content_len=None) # self.assertEqual(ctx.exception.code, 411) with self.assertRaises(HTTPError) as ctx: self._send_webhook_msg(ip, port, 'dummy-payload', content_len='not-a-number') self.assertEqual(ctx.exception.code, 403) finally: self.updater._stop_httpd() thr.join() def _send_webhook_msg(self, ip, port, payload_str, url_path='', content_len=-1, content_type='application/json', get_method=None): headers = { 'content-type': content_type, } if not payload_str: content_len = None payload = None else: payload = bytes(payload_str, encoding='utf-8') if content_len == -1: content_len = len(payload) if content_len is not None: headers['content-length'] = str(content_len) url = 'http://{ip}:{port}/{path}'.format(ip=ip, port=port, path=url_path) req = Request(url, data=payload, headers=headers) if get_method is not None: req.get_method = get_method return urlopen(req) def signalsender(self): sleep(0.5) os.kill(os.getpid(), signal.SIGTERM) def test_idle(self): self._setup_updater('Test6', messages=0) self.updater.start_polling(poll_interval=0.01) Thread(target=self.signalsender).start() self.updater.idle() # If we get this far, idle() ran through sleep(1) self.assertFalse(self.updater.running) def test_createBot(self): updater = Updater('123:abcd') self.assertIsNotNone(updater.bot) def test_mutualExclusiveTokenBot(self): bot = Bot('123:zyxw') self.assertRaises(ValueError, Updater, token='123:abcd', bot=bot) def test_noTokenOrBot(self): self.assertRaises(ValueError, Updater)
class UpdaterTest(BaseTest, unittest.TestCase): """ This object represents Tests for Updater, Dispatcher, WebhookServer and WebhookHandler """ def setUp(self): self.updater = Updater('', workers=2) self.received_message = None self.message_count = 0 self.lock = Lock() def tearDown(self): self.updater.stop() def reset(self): self.message_count = 0 self.received_message = None def telegramHandlerTest(self, bot, update): self.received_message = update.message.text self.message_count += 1 @run_async def asyncHandlerTest(self, bot, update): sleep(1) with self.lock: self.received_message = update.message.text self.message_count += 1 def stringHandlerTest(self, bot, update): self.received_message = update self.message_count += 1 def additionalArgsTest(self, bot, update, update_queue, args): self.received_message = update self.message_count += 1 if args[0] == 'resend': update_queue.put('/test5 noresend') elif args[0] == 'noresend': pass def errorRaisingHandlerTest(self, bot, update): raise TelegramError(update) def errorHandlerTest(self, bot, update, error): self.received_message = error.message self.message_count += 1 def test_addRemoveTelegramMessageHandler(self): print('Testing add/removeTelegramMessageHandler') bot = MockBot('Test') self.updater.bot = bot d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, 'Test') # Remove handler d.removeTelegramMessageHandler(self.telegramHandlerTest) self.reset() bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addTelegramMessageHandlerMultipleMessages(self): print('Testing addTelegramMessageHandler and send 100 messages...') self.updater.bot = MockBot('Multiple', 100) self.updater.dispatcher.addTelegramMessageHandler( self.telegramHandlerTest) self.updater.start_polling(0.0) sleep(.5) self.assertEqual(self.received_message, 'Multiple') self.assertEqual(self.message_count, 100) def test_addRemoveTelegramRegexHandler(self): print('Testing add/removeStringRegexHandler') bot = MockBot('Test2') self.updater.bot = bot d = self.updater.dispatcher regobj = re.compile('Te.*') self.updater.dispatcher.addTelegramRegexHandler( regobj, self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, 'Test2') # Remove handler d.removeTelegramRegexHandler(regobj, self.telegramHandlerTest) self.reset() bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveTelegramCommandHandler(self): print('Testing add/removeTelegramCommandHandler') bot = MockBot('/test') self.updater.bot = bot d = self.updater.dispatcher self.updater.dispatcher.addTelegramCommandHandler( 'test', self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, '/test') # Remove handler d.removeTelegramCommandHandler('test', self.telegramHandlerTest) self.reset() bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveUnknownTelegramCommandHandler(self): print('Testing add/removeUnknownTelegramCommandHandler') bot = MockBot('/test2') self.updater.bot = bot d = self.updater.dispatcher self.updater.dispatcher.addUnknownTelegramCommandHandler( self.telegramHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, '/test2') # Remove handler d.removeUnknownTelegramCommandHandler(self.telegramHandlerTest) self.reset() bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveStringRegexHandler(self): print('Testing add/removeStringRegexHandler') bot = MockBot('', messages=0) self.updater.bot = bot d = self.updater.dispatcher d.addStringRegexHandler('Te.*', self.stringHandlerTest) queue = self.updater.start_polling(0.01) queue.put('Test3') sleep(.1) self.assertEqual(self.received_message, 'Test3') # Remove handler d.removeStringRegexHandler('Te.*', self.stringHandlerTest) self.reset() queue.put('Test3') sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveStringCommandHandler(self): print('Testing add/removeStringCommandHandler') bot = MockBot('', messages=0) self.updater.bot = bot d = self.updater.dispatcher d.addStringCommandHandler('test3', self.stringHandlerTest) queue = self.updater.start_polling(0.01) queue.put('/test3') sleep(.1) self.assertEqual(self.received_message, '/test3') # Remove handler d.removeStringCommandHandler('test3', self.stringHandlerTest) self.reset() queue.put('/test3') sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveUnknownStringCommandHandler(self): print('Testing add/removeUnknownStringCommandHandler') bot = MockBot('/test') self.updater.bot = bot d = self.updater.dispatcher d.addUnknownStringCommandHandler(self.stringHandlerTest) queue = self.updater.start_polling(0.01) queue.put('/test4') sleep(.1) self.assertEqual(self.received_message, '/test4') # Remove handler d.removeUnknownStringCommandHandler(self.stringHandlerTest) self.reset() bot.send_messages = 1 sleep(.1) self.assertTrue(None is self.received_message) def test_addRemoveErrorHandler(self): print('Testing add/removeErrorHandler') bot = MockBot('', messages=0) self.updater.bot = bot d = self.updater.dispatcher d.addErrorHandler(self.errorHandlerTest) queue = self.updater.start_polling(0.01) error = TelegramError("Unauthorized.") queue.put(error) sleep(.1) self.assertEqual(self.received_message, "Unauthorized.") # Remove handler d.removeErrorHandler(self.errorHandlerTest) self.reset() queue.put(error) sleep(.1) self.assertTrue(None is self.received_message) def test_errorInHandler(self): print('Testing error in Handler') bot = MockBot('', messages=0) self.updater.bot = bot d = self.updater.dispatcher d.addStringRegexHandler('.*', self.errorRaisingHandlerTest) self.updater.dispatcher.addErrorHandler(self.errorHandlerTest) queue = self.updater.start_polling(0.01) queue.put('Test Error 1') sleep(.1) self.assertEqual(self.received_message, 'Test Error 1') def test_errorOnGetUpdates(self): print('Testing error on getUpdates') bot = MockBot('', raise_error=True) self.updater.bot = bot d = self.updater.dispatcher d.addErrorHandler(self.errorHandlerTest) self.updater.start_polling(0.01) sleep(.1) self.assertEqual(self.received_message, "Test Error 2") def test_addRemoveTypeHandler(self): print('Testing add/removeTypeHandler') bot = MockBot('', messages=0) self.updater.bot = bot d = self.updater.dispatcher d.addTypeHandler(dict, self.stringHandlerTest) queue = self.updater.start_polling(0.01) payload = {"Test": 42} queue.put(payload) sleep(.1) self.assertEqual(self.received_message, payload) # Remove handler d.removeTypeHandler(dict, self.stringHandlerTest) self.reset() queue.put(payload) sleep(.1) self.assertTrue(None is self.received_message) def test_runAsync(self): print('Testing @run_async') bot = MockBot('Test5', messages=2) self.updater.bot = bot d = self.updater.dispatcher d.addTelegramMessageHandler(self.asyncHandlerTest) self.updater.start_polling(0.01) sleep(1.2) self.assertEqual(self.received_message, 'Test5') self.assertEqual(self.message_count, 2) def test_additionalArgs(self): print('Testing additional arguments for handlers') self.updater.bot = MockBot('', messages=0) self.updater.dispatcher.addStringCommandHandler( 'test5', self.additionalArgsTest) queue = self.updater.start_polling(0.01) queue.put('/test5 resend') sleep(.1) self.assertEqual(self.received_message, '/test5 noresend') self.assertEqual(self.message_count, 2) def test_webhook(self): print('Testing Webhook') bot = MockBot('', messages=0) self.updater.bot = bot d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) # Select random port for travis port = randrange(1024, 49152) self.updater.start_webhook('127.0.0.1', port, './tests/test_updater.py', './tests/test_updater.py', listen='127.0.0.1') sleep(0.5) # SSL-Wrapping will fail, so we start the server without SSL Thread(target=self.updater.httpd.serve_forever).start() # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester"), datetime.now(), GroupChat(1, "Test Group")) message.text = "Webhook Test" update = Update(1) update.message = message try: payload = bytes(update.to_json(), encoding='utf-8') except TypeError: payload = bytes(update.to_json()) header = { 'content-type': 'application/json', 'content-length': str(len(payload)) } r = Request('http://127.0.0.1:%d/TOKEN' % port, data=payload, headers=header) urlopen(r) sleep(1) self.assertEqual(self.received_message, 'Webhook Test') print("Test other webhook server functionalites...") request = Request('http://localhost:%d/webookhandler.py' % port) response = urlopen(request) self.assertEqual(b'', response.read()) self.assertEqual(200, response.code) request.get_method = lambda: 'HEAD' response = urlopen(request) self.assertEqual(b'', response.read()) self.assertEqual(200, response.code) # Test multiple shutdown() calls self.updater.httpd.shutdown() self.updater.httpd.shutdown() self.assertTrue(True) def signalsender(self): sleep(0.5) os.kill(os.getpid(), signal.SIGTERM) def test_idle(self): print('Testing idle') self.updater.bot = MockBot('Test6', messages=0) self.updater.start_polling(poll_interval=0.01) Thread(target=self.signalsender).start() self.updater.idle() # If we get this far, idle() ran through sleep(1) self.updater.running = False