def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(secrets.bot_token) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addHandler(CommandHandler("start", start)) dp.addHandler(CommandHandler("help", help)) dp.addHandler(CommandHandler("random", random)) dp.addHandler(CommandHandler("suicide", suicide)) dp.addHandler(CommandHandler("developer", developer)) # inline query dp.addHandler(InlineQueryHandler(search)) # on noncommand i.e message - echo the message on Telegram dp.addHandler(MessageHandler([Filters.text], 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(telegram_token) # 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", helper)) # on noncommand i.e message dp.add_handler(MessageHandler([Filters.text], chat)) # inline keyboard handler #dp.add_handler(telegram.ext.CallbackQueryHandler(scroll)) # TODO: update messages with time information # log all errors dp.add_error_handler(error) # Start the Bot updater.start_webhook(listen='95.163.114.6', port=88, url_path='CroCodeBot', key='/home/user/cert/private.key', cert='/home/user/cert/cert.pem', webhook_url='https://95.163.114.6:88/CroCodeBot') updater.idle()
def main(): global users users = storer.restore('users') if users is None: users = {} global job_queue # Create the EventHandler and pass it your bot's token. token = read_token() updater = Updater(token) job_queue = updater.job_queue job_queue.put(check_thresholds, BALANCE_CHECK_INTERVAL_SEC, repeat=True) # Get the dispatcher to register handlers dp = updater.dispatcher # This is how we add handlers for Telegram messages dp.addHandler(CommandHandler("help", help)) dp.addHandler(CommandHandler("start", start)) dp.addHandler(CommandHandler("getcardbalance", get_card_balance, pass_args=True)) dp.addHandler(CommandHandler("addcard", add_card, pass_args=True)) dp.addHandler(CommandHandler("removecard", remove_card, pass_args=True)) dp.addHandler(CommandHandler("getcards", get_cards)) dp.addHandler(CommandHandler("setthreshold", set_threshold, pass_args=True)) updater.start_polling() updater.idle()
def main(): """Run bot.""" updater = Updater("542522228:AAEu6tYYENVsWml6s0VyqySndSGvi41HSrc") # 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", start)) dp.add_handler(CommandHandler("set", set_timer, pass_args=True, pass_job_queue=True, pass_chat_data=True)) dp.add_handler(CommandHandler("unset", unset, pass_chat_data=True)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Block 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()
def main(): print("memers default value:") print(memers) load_memers() print("loaded memers:") print(memers) updater = Updater(apikey) dp = updater.dispatcher jqueue = updater.job_queue dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("test", test)) dp.add_handler(CommandHandler("ping", ping)) dp.add_handler(CommandHandler("time", time)) dp.add_handler(CommandHandler("boat", boat)) dp.add_handler(CommandHandler("ebin", ebin)) dp.add_handler(CommandHandler("stats", stats)) dp.add_handler(CommandHandler("chatinfo", chatinfo)) dp.add_handler(CommandHandler("drop", drop)) dp.add_handler(CommandHandler("shop", shop)) updater.dispatcher.add_handler(CallbackQueryHandler(shopbutton)) dp.add_handler(MessageHandler([Filters.text], parse)) dp.add_error_handler(error) 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(token="BOT_TOKEN") # Get the dispatcher to register handlers dp = updater.dispatcher # simple start function dp.add_handler(CommandHandler("start", start_callback)) # Add command handler to start the payment invoice dp.add_handler(CommandHandler("shipping", start_with_shipping_callback)) dp.add_handler(CommandHandler("noshipping", start_without_shipping_callback)) # Optional handler if your product requires shipping dp.add_handler(ShippingQueryHandler(shipping_callback)) # Pre-checkout handler to final check dp.add_handler(PreCheckoutQueryHandler(precheckout_callback)) # Success! Notify your user! dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback)) # 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()
def main(): updater = Updater(token=TOKEN) dispatcher = updater.dispatcher # Handlers start_handler = CommandHandler('start', start, pass_args=True) help_handler = CommandHandler('help', start, pass_args=True) date_insta_top_posts_handler = CommandHandler('date', date_insta_top_posts, pass_args=True) top_post_handler = CommandHandler('top', top_post, pass_args=True) add_handler = CommandHandler("add", add, pass_args=True) message_handler = CommandHandler("message", message, pass_args=True) # Dispatchers dispatcher.add_handler(date_insta_top_posts_handler) dispatcher.add_handler(top_post_handler) dispatcher.add_handler(add_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(message_handler) dispatcher.add_handler(MessageHandler(Filters.text, chat)) dispatcher.add_error_handler(error) updater.start_polling() updater.idle()
def main(): """ Main function of the bot """ # Create a Botan tracker object botan = Botan(CONFIGURATION["botan_token"]) # Last user request last_request = {} # Create the EventHandler and pass it your bot's token. token = CONFIGURATION["telegram_token"] updater = Updater(token) # on different commands - answer in Telegram updater.dispatcher.add_handler(CommandHandler("help", help_command)) updater.dispatcher.add_handler(RegexHandler("/r/.*", lambda bot, update: random_post(bot, update, last_request))) updater.dispatcher.add_handler(CommandHandler("more", lambda bot, update: random_post(bot, update, last_request))) updater.dispatcher.add_handler(RegexHandler("/r/.*", lambda bot, update: any_message(update, botan)), group=1) updater.dispatcher.add_handler(CommandHandler("more", lambda bot, update: any_message(update, botan)), group=1) # log all errors updater.dispatcher.add_error_handler(lambda bot, update, error: error_handler(update, 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(): token = config.get('TOKEN') if token is None: print("Please, configure your token first") sys.exit(1) updater = Updater(token) dispatcher = updater.dispatcher # on different commands - answer in Telegram dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("help", help)) dispatcher.add_handler(CommandHandler("apod", apod)) dispatcher.add_handler(CommandHandler("autoapod", autoapod, pass_job_queue=True)) dispatcher.add_handler(CommandHandler("stopautoapod", stopautoapod, pass_job_queue=True)) dispatcher.add_handler(CommandHandler("tiempo", tiempo, pass_args=True)) dispatcher.add_handler(CommandHandler("faselunar", faselunar)) dispatcher.add_handler(CommandHandler("manchas", manchas)) dispatcher.add_handler(CommandHandler("estanoche", estanoche)) # on noncommand i.e message - echo the message on Telegram dispatcher.add_handler(MessageHandler([Filters.text], randomchat)) # log all errors dispatcher.add_error_handler(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(): # Read secret token from file with open('easy_python_bot_token', 'r') as easy_python_bot_token_file: easy_python_bot_token = easy_python_bot_token_file.readline() # Create the EventHandler and pass it your bot's token. updater = Updater(easy_python_bot_token) # 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)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler([Filters.text], text_message_handler)) # log all errors dp.add_error_handler(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(): print 'start' # Create the EventHandler and pass it your bot's token. updater = Updater(BOT_TOKEN) print 'updated' # Get the dispatcher to register handlers dp = updater.dispatcher print 'get dispatcher' # on different commands - answer in Telegram dp.addHandler(CommandHandler("start", start)) dp.addHandler(CommandHandler("help", help)) dp.addHandler(CommandHandler("vn-search", vn_search)) print 'add handlers' # on noncommand i.e message - echo the message on Telegram dp.addHandler(MessageHandler([filters.TEXT], echo)) print 'message handler' # log all errors dp.addErrorHandler(error) print 'add error' # Start the Bot updater.start_polling() print '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 passs it your bot's token. updater = Updater(os.environ['LOGBOT']) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addHandler(CommandHandler("start", start)) dp.addHandler(CommandHandler("help", help)) # on noncommand i.e message - echo the message on Telegram dp.addHandler(MessageHandler([Filters.text],reply)) # log all errors dp.addErrorHandler(error) # Start the Bot updater.start_polling() print 'Bot Started!!\n' # 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 __init__(self): self.config_instance = self.config_init() updater = Updater(self.config_instance.TELEGRAM_BOT_KEY) dp = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename=self.config_instance.LOG_FILE ) dp.add_handler(MessageHandler( [Filters.text], self.command_check_resps)) dp.add_handler(CommandHandler("start", self.command_start)) dp.add_handler(CommandHandler( "roll", self.command_roll, pass_args=True)) dp.add_handler(CommandHandler("leaderboard", self.command_leaderboard)) dp.add_error_handler(self.error) jq = updater.job_queue jq.put(self.update_all_timers, 1) self.logger.info("Started... ") updater.start_polling() updater.idle()
def main(): """Start the bot.""" # 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.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) # 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()
def main(): updater = Updater(bot_token) # Get the dispatcher to register handlers dp = updater.dispatcher unknown_handler = MessageHandler([Filters.command], unknown) echo_handler = MessageHandler([Filters.text], echo) help_handler = CommandHandler('help', help_func) schedule_handler = CommandHandler("schedule", schedule) short_schedule_handler = CommandHandler("s", schedule, pass_args=True) routes_handler = CommandHandler("i", routes, pass_args=True) dp.add_handler(CommandHandler('start', start_command)) dp.add_handler(echo_handler) dp.add_handler(help_handler) dp.add_handler(schedule_handler) dp.add_handler(short_schedule_handler) dp.add_handler(routes_handler) dp.add_handler(unknown_handler) dp.add_handler(CallbackQueryHandler(answer_query)) # log all errors dp.add_error_handler(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(): config = configparser.ConfigParser() config.read('config.ini') # Create the EventHandler and pass it your bot's token. updater = Updater(config['init']['token']) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", start) dp.addTelegramCommandHandler("add", add) dp.addTelegramCommandHandler("help", help) # on noncommand i.e message - echo the message on Telegram dp.addTelegramMessageHandler(message) # 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 __init__(self): self.a = Api() # Create the EventHandler and pass it your bot's token. updater = Updater(settings.TELEGRAM_TOKEN) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addTelegramCommandHandler("start", self.start) # dp.addTelegramCommandHandler("help", help) # 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 forecast_info global dp loadmodules() forecast_info = load_db() updater = Updater(TOKEN) dp = updater.dispatcher loadcommands() dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("rehash", rehash)) dp.add_handler(CommandHandler("forecast", forecast)) dp.add_handler(CommandHandler("weather", weather)) dp.add_handler(CommandHandler("setlocation", set_local)) dp.add_handler(MessageHandler([Filters.text], stats)) dp.add_error_handler(error) updater.start_polling(timeout=5) while True: text = raw_input() if text == 'stop': save_db(forecast_info) updater.stop() break
def main(): global update_queue global screen #@VideoBoxBot updater = Updater("145378027:AAFB2YiOzHnCQ55xD1VDjGTprwKhGI2VLlk") # Get the dispatcher to register handlers dp = updater.dispatcher # Definisce gli handler di gestione dei comandi dp.add_handler(CommandHandler("start", cmd_start)) dp.add_handler(CommandHandler("cancel", cmd_cancel)) dp.add_handler(MessageHandler([Filters.text], text_handler)) dp.add_handler(MessageHandler([Filters.video], video_handler)) dp.add_handler(MessageHandler([Filters.document], document_handler)) # log all errors dp.add_error_handler(error) # Start the Bot update_queue = updater.start_polling() try: # 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() except KeyboardInterrupt: print "Exit"
def main(): # Create the Updater and pass it your bot's token. updater = Updater(TOKEN, workers=10) # Get the dispatcher to register handlers dp = updater.dispatcher dp.add_handler(CommandHandler("start", help)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler('welcome', set_welcome, pass_args=True)) dp.add_handler(CommandHandler('goodbye', set_goodbye, pass_args=True)) dp.add_handler(CommandHandler('disable_goodbye', disable_goodbye)) dp.add_handler(CommandHandler("lock", lock)) dp.add_handler(CommandHandler("unlock", unlock)) dp.add_handler(CommandHandler("quiet", quiet)) dp.add_handler(CommandHandler("unquiet", unquiet)) dp.add_handler(MessageHandler([Filters.status_update], empty_message)) dp.add_handler(MessageHandler([Filters.text], stats)) dp.add_error_handler(error) update_queue = updater.start_polling(timeout=30, clean=False) updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("181560082:AAHbTzTUj6_onF8p_iClYODVjFyreSvAEZg") # 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("temperatura", obtentemp)) dp.add_handler(CommandHandler("luz", obtenluz)) # 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 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(): # Read config file with open("/home/pi/telegram-secretsanta/token.txt") as f: bot_token = f.readline().strip() # Create the Updater and pass it your bot's token. updater = Updater(bot_token) # Get the dispatcher to register handlers dp = updater.dispatcher # on noncommand i.e message - echo the message on Telegram dp.add_handler(InlineQueryHandler(new_secret_santa)) dp.add_handler(CallbackQueryHandler(button_click_callback)) # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", help)) dp.add_handler(CommandHandler("help", help)) # log all errors dp.add_error_handler(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()
def main(): mybot = Updater("368736105:AAGLQaNZ_tWNOEg5kCQ4A0M8LEdgGFitKD8", request_kwargs=PROXY) dp = mybot.dispatcher dp.add_handler(CommandHandler("start", greet_user)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) mybot.start_polling() mybot.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.add_handler(CommandHandler("start", c.startGame)) dp.add_handler(CommandHandler("stop", c.stop)) dp.add_handler(CommandHandler("creategame", c.createGame)) dp.add_handler(CommandHandler("join", c.joinGame)) dp.add_handler(CommandHandler("game", c.getGame)) dp.add_handler(CommandHandler("hello", c.hello)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler([Filters.text], c.checkPlays)) # 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(): init() updater = Updater(TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("ping", ping)) dp.add_handler(CommandHandler("nyang", nyang)) dp.add_handler(CommandHandler("rand", rand)) dp.add_handler(CommandHandler("sysstat", lambda x, y: stat(x, y, 'sys'))) dp.add_handler(CommandHandler("cpustat", lambda x, y: stat(x, y, 'cpu'))) dp.add_handler(CommandHandler("memstat", lambda x, y: stat(x, y, 'mem'))) dp.add_handler(CommandHandler("webstat", lambda x, y: stat(x, y, 'web'))) dp.add_handler(CommandHandler("diskstat", lambda x, y: stat(x, y, 'disk'))) dp.add_handler(CommandHandler("procstat", lambda x, y: stat(x, y, 'proc'))) dp.add_handler(CommandHandler("bakstat", lambda x, y: stat(x, y, 'bak'))) dp.add_handler(MessageHandler([Filters.command], unknown)) dp.add_handler(MessageHandler([Filters.text], echo)) dp.add_error_handler(error) updater.start_polling() updater.idle()
def main(): # Create the EventHandler and pass it your bot's token. token = 'TOKEN' updater = Updater(token, workers=10) # Get the dispatcher to register handlers dp = updater.dispatcher # This is how we add handlers for Telegram messages dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) # Message handlers only receive updates that don't contain commands dp.add_handler(MessageHandler([Filters.text], message)) # Regex handlers will receive all updates on which their regex matches, # but we have to add it in a separate group, since in one group, # only one handler will be executed dp.add_handler(RegexHandler('.*', any_message), group=1) # String handlers work pretty much the same. Note that we have to tell # the handler to pass the args or update_queue parameter dp.add_handler(StringCommandHandler('reply', cli_reply, pass_args=True)) dp.add_handler(StringRegexHandler('[^/].*', cli_noncommand, pass_update_queue=True)) # All TelegramErrors are caught for you and delivered to the error # handler(s). Other types of Errors are not caught. dp.add_error_handler(error) # Start the Bot and store the update Queue, so we can insert updates update_queue = updater.start_polling(timeout=10) ''' # Alternatively, run with webhook: update_queue = updater.start_webhook('0.0.0.0', 443, url_path=token, cert='cert.pem', key='key.key', webhook_url='https://example.com/%s' % token) # Or, if SSL is handled by a reverse proxy, the webhook URL is already set # and the reverse proxy is configured to deliver directly to port 6000: update_queue = updater.start_webhook('0.0.0.0', 6000) ''' # Start CLI-Loop while True: text = input() # Gracefully stop the event handler if text == 'stop': updater.stop() break # else, put the text into the update queue to be handled by our handlers elif len(text) > 0: update_queue.put(text)
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(telegram_token) # 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", helper)) # on noncommand i.e message dp.add_handler(MessageHandler([Filters.text], chat)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_webhook(listen='95.163.114.6', # 95.163.114.6 port=80, url_path='MaraphonBot', key='/home/user/cert/private.key', cert='/home/user/cert/cert.pem', webhook_url='https://95.163.114.6:80/MaraphonBot') updater.idle()
def main(): logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) random.seed(time.time()) config = load_configuration() # db.init(config['db_url']) updater = Updater(token=config['auth_token']) dispatcher = updater.dispatcher dispatcher.add_handler(funyreplies.comrade_handler) dispatcher.add_handler(funyreplies.its_not_handler) dispatcher.add_handler(misc.leave_chat_handler) #dispatcher.add_handler(misc.status_update_handler) #dispatcher.add_handler(misc.roulette_handler) dispatcher.add_handler(misc.help_handler) dispatcher.add_handler(misc.until_ny_handler) dispatcher.add_handler(timers.set_timer_handler) dispatcher.add_handler(timers.clear_all_timers_handler) dispatcher.add_handler(misc.log_handler, -1) updater.start_polling(clean=True)
def main(): # Create the Updater and pass it your bot's token. updater = Updater("181752127:AAFX10TTymBCbB4_0RKG5LxtoBJKgyYUulM") # 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("pay", pay) dp.addTelegramCommandHandler("fee", fee) dp.addTelegramCommandHandler("history", history) dp.addTelegramCommandHandler("confirm", confirm) # 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()
class Connector: """Connector class for the Telegram bot API.""" def __init__(self, bot): """Will load the api token from $TELEGRAM_API_TOKEN.""" self.bot = bot token = os.getenv('TELEGRAM_API_TOKEN') if token is None: print('TELEGRAM_API_TOKEN not set. Exiting...') sys.exit(1) self.updater = Updater(token=token) self.dispatcher = self.updater.dispatcher self.dispatcher.add_handler(MessageHandler(None, self.parse_incoming)) def listen(self): """Listen for messages.""" self.updater.start_polling() self.updater.idle() def parse_incoming(self, bot, incoming): """Transform incoming telegram info into format Chattie can parse.""" resp = self.bot.parse_message(incoming.message.text) for r in resp: bot.sendMessage(chat_id=incoming.message.chat_id, text=r)
try: # open the file txt = open(filename) # read the file: load each row in an element of the list without "/n" tasks_list = txt.read().splitlines() # close the file txt.close() except IOError: # File not found! We work with an empty list print("File not found!") exit() updater = Updater(token='590898204:AAGnj2CzA2VTOUFeeycawi6VRuWOeddxkyA') # add an handler to start the bot replying with the list of available commands dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', start)) # on non-command textual messages - echo the message on Telegram dispatcher.add_handler(MessageHandler(Filters.text, echo)) # add an handler to insert a new task in the list newTask_handler = CommandHandler('newTask', new_task, pass_args=True) dispatcher.add_handler(newTask_handler) # add an handler to remove the first occurence of a specific task from the list removeTask_handler = CommandHandler('removeTask', remove_task,
import time from telegram.ext import Updater from telegram.ext import CommandHandler from telegram.error import (TelegramError, Unauthorized, BadRequest, TimedOut, ChatMigrated, NetworkError) import urllib.request from requests import ConnectionError import requests import urllib3 import io import re # running on telegram fridgobot updater = Updater(token='TOKEN') dispatcher = updater.dispatcher jq = updater.job_queue # user management users = [] def start(bot, update): if update.message.chat_id not in users: users.append(update.message.chat_id) print(update.message.chat_id) bot.send_message(chat_id=update.message.chat_id, text='- Feinsaubalarm abonniert -')
def getJson(useText, jsondata): keys = [key for key in jsondata] returnvalue = "안물안궁" for key in keys: if key in useText: returnvalue = jsondata[key] return returnvalue def get_message(update, context): with open("./json_test.json", "r", encoding='UTF8') as json_file: jsondata = json.load(json_file) useText = update.message.text if "실시간차트" in useText: update.message.reply_text(getMelonChart()) else: update.message.reply_text(getJson(useText, jsondata)) updater = Updater(bot_id, use_context=True) message_handler = MessageHandler(Filters.text, get_message) updater.dispatcher.add_handler(message_handler) updater.start_polling(timeout=3, clean=True) updater.idle()
def clean_up(conn, cur): cur.close() conn.close() if __name__ == "__main__": TOKEN = '' # telegram bot related information bot = telegram.Bot(token=TOKEN) # Initializing the DB conn, cur = connect_sqlite3("announcement.db") updater = Updater(token=TOKEN, use_context=True, request_kwargs={ 'read_timeout': 6, 'connect_timeout': 7 }) dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) start_handler = CommandHandler('start', start) leave_handler = CommandHandler('leave', leave) dispatcher.add_handler(start_handler) dispatcher.add_handler(leave_handler) updater.start_polling() while True:
soup = bs(html, 'html.parser') days = soup.findAll('span', {'class': 'date-time'}) temps = soup.select('#twc-scrollabe > table > tbody > tr > td.temp > div') total = '' for day, temp in zip(days, temps): update.message.reply_text(day.text + " :" + temp.text) # help reply function def help_command(bot, update) : update.message.reply_text("/help = what can I help? \n/weather = weather condition? ") # weather condition function def weather_command(bot, update) : update.message.reply_text("Type your zipcode: ") updater = Updater(my_token) #Filters.text는 텍스트에 대해 응답하며 이때 get_message 함수를 호출합니다. #get_message 호출시 got text 와 받은 메세지를 답장합니다. message_handler = MessageHandler(Filters.text, get_message) updater.dispatcher.add_handler(message_handler) help_handler = CommandHandler('help', help_command) updater.dispatcher.add_handler(help_handler) weather_handler = CommandHandler('weather', weather_command) updater.dispatcher.add_handler(weather_handler) photo_handler = MessageHandler(Filters.photo, get_photo) updater.dispatcher.add_handler(photo_handler)
from telegram.ext import Updater from telegram import Poll, Bot, PollOption updater = Updater(token='1022567655:AAGjqp1EcNQKQlFlzMIr6MpLQLIoi_YJ4YM', use_context=True) text = open('third round/test.txt', "r", encoding="utf-8") '''this is the file that contains all the tweets''' lines = text.readlines() dispatcher = updater.dispatcher import logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def start(update, context): global lines context.bot.send_message(chat_id=update.effective_chat.id, text=lines[0]) import logging from telegram.ext import CommandHandler start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) def instruction(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text='ጽሁፉ አዎንታዊ ከሆነ "1"ን አሉታዊ "2"ን ገለልትኛ ከሆነ "3" ይጻፉ')
class CoronaBot: def __init__(self, token): self.updater = Updater(token, use_context=True) self.job_queue = self.updater.job_queue self.users = UsersDB('./users.pkl') self.last_news = deque(maxlen=5) self.dp = self.updater.dispatcher self.dp.add_handler(CommandHandler("start", self.start)) self.dp.add_handler(CommandHandler("stop", self.stop)) self.dp.add_handler(CommandHandler("help", self.help)) self.dp.add_handler(CommandHandler("u", self.get_update)) self.dp.add_handler(CommandHandler("latest", self.get_latest)) self.dp.add_handler(MessageHandler(Filters.text, self.echo)) self.dp.add_error_handler(self.error) self.jobs = [] self.jobs.append(self.job_queue.run_repeating(self.send_updates2users, 60)) # , context=update def run(self): self.updater.start_polling() self.updater.idle() def send_updates2users(self, job_context): new_items = source_1.get_new_items() + source_2.get_new_items() + source_3.get_new_items() for new_item in new_items: translated_item = translator.translate(new_item, dest='en', src='de').text self.last_news.append(translated_item) for chat_it in self.users.db: job_context.bot.send_message(chat_id=chat_it, text=translated_item, parse_mode=ParseMode.MARKDOWN) # job_context.bot.send_message(chat_id=job_context.job.context.message.chat.id, text='Alarm') WORKS! # job_context.job.context.message.reply_text('Alarm2')WORKS! def start(self, update, context): """Send a message when the command /start is issued.""" chat_id = update.effective_chat.id if self.users.add(chat_id): update.message.reply_text('Hi!') context.bot.send_message(218135295, text=f'New user: {chat_id}, {update.message.chat}') else: update.message.reply_text('Hello again!') def stop(self, update, context): """Send a message when the command /start is issued.""" chat_id = update.effective_chat.id if self.users.delete(chat_id): update.message.reply_text('May the God be with you!') context.bot.send_message(218135295, text=f'deleted user: {chat_id}') else: update.message.reply_text('Byyyyeeee!') def help(self, update, context): """Send a message when the command /help is issued.""" update.message.reply_text('Help!') if update.effective_chat.id == 218135295: print(self.users.db) update.message.reply_text(str(self.users.db)) def echo(self, update, context): """Echo the user message.""" update.message.reply_text(update.message.text) def error(self, update, context): """Log Errors caused by Updates.""" print(f'Update "{update}" caused error "{context.error}"') context.bot.send_message(218135295, text=f'error: {context.error}') def get_update(self, update, context): """Get update on the virus.""" new_items = source_1.get_all_items()[-2:] + source_2.get_all_items()[-2:] + source_3.get_all_items()[-2:] for item in new_items: update.message.reply_text(item) def get_latest(self, update, context): """Get latest update on the virus.""" for item in self.last_news: context.bot.send_message(update.message.chat.id, text=item, parse_mode=ParseMode.MARKDOWN)
__author__ = 'alexsviridov' # import telebot BOT_TOKEN = "660361487:AAFBBtv8y1pfqY-pPekyT3Qbom9RMWD0Glg" # Настройки from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import os from DB import BotDatabase #BOT_TOKEN = "TOKEN" PORT = int(os.environ.get('PORT', '8443')) updater = Updater(BOT_TOKEN) dispatcher = updater.dispatcher import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') class CalcBot: Value = 0.0 def __init__(self): self.db = BotDatabase() self.Value = self.db.getValue()
def start_webhook(token: str, db_uri: str, port: int): setup_database_engine(db_uri) updater = Updater(token, use_context=True) setup_handlers(updater) updater.start_webhook(port=port) updater.idle()
set_techo), MessageHandler(Filters.regex(constantes.REGEX_ONLY_STRINGS), error_letra) ], S_ERROR: [ MessageHandler(Filters.regex(constantes.REGEX_ONLY_NUMBERS), set_error), MessageHandler(Filters.regex(constantes.REGEX_ONLY_STRINGS), error_letra) ], }, fallbacks=[MessageHandler(Filters.regex('^Volver$'), done)]) if __name__ == '__main__': import logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) BOT_KEY = os.environ['BOT_KEY'] updater = Updater(token=BOT_KEY, use_context=True) dispatcher = updater.dispatcher # dispatcher.add_handler(CommandHandler('start', edna)) dispatcher.add_handler(tevi_conversation_handler()) updater.start_polling()
import logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") def echo(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text) if __name__ == '__main__': updater = Updater('1677667809:AAHH2KzZBHJl4NPS8Jqjrw4bMl6VYviQ8ac') dispatcher = updater.dispatcher start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) echo_handler = MessageHandler(Filters.text & (~Filters.command), echo) dispatcher.add_handler(echo_handler) def caps(update, context): text_caps = ' '.join(context.args).upper() context.bot.send_message(chat_id=update.effective_chat.id, text=text_caps) caps_handler = CommandHandler('caps', caps)
def start_polling(token: str, db_uri: str): setup_database_engine(db_uri) updater = Updater(token, use_context=True) setup_handlers(updater) updater.start_polling() updater.idle()
class TestInlineBot(unittest.TestCase): def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # And an InlineQueryGenerator and updater (for use with the bot.) self.iqg = InlineQueryGenerator(self.bot) self.updater = Updater(bot=self.bot) def test_inline_bot(self): # create some handlers and add them def escape_markdown(text): """Helper function to escape telegram markup symbols""" escape_chars = '\*_`\[' return re.sub(r'([%s])' % escape_chars, r'\\\1', text) def inlinequery(update, context): query = update.inline_query.query results = list() results.append( InlineQueryResultArticle( id=str(uuid4()), title="Caps", input_message_content=InputTextMessageContent( query.upper()))) results.append( InlineQueryResultArticle( id=str(uuid4()), title="Bold", input_message_content=InputTextMessageContent( "*%s*" % escape_markdown(query), parse_mode=ParseMode.MARKDOWN))) results.append( InlineQueryResultArticle( id=str(uuid4()), title="Italic", input_message_content=InputTextMessageContent( "_%s_" % escape_markdown(query), parse_mode=ParseMode.MARKDOWN))) update.inline_query.answer(results) dp = self.updater.dispatcher dp.add_handler(InlineQueryHandler(inlinequery)) self.updater.start_polling() # Now test the handler u1 = self.iqg.get_inline_query(query="test data") self.bot.insertUpdate(u1) data = self.bot.sent_messages[-1] self.assertEqual(len(data['results']), 3) results = data['results'] self.assertEqual(results[0]['title'], "Caps") self.assertEqual(results[0]['input_message_content']['message_text'], "TEST DATA") self.assertEqual(results[1]['title'], "Bold") self.assertEqual(results[1]['input_message_content']['message_text'], "*test data*") self.assertEqual(results[2]['title'], "Italic") self.assertEqual(results[2]['input_message_content']['message_text'], "_test data_") self.updater.stop()
def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # And an InlineQueryGenerator and updater (for use with the bot.) self.iqg = InlineQueryGenerator(self.bot) self.updater = Updater(bot=self.bot)
import json import random import os import dotenv from telegram.ext import Updater dotenv.load_dotenv('.env') TOKEN = os.getenv('TOKEN') updater = Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher import logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def start(update, context): context.bot.send_message( chat_id=update.effective_chat.id, text= "Hi there , Im random Roti ( Rules Of The Internet ) bot , send /rroti to get a random rule .\n\n Made by github.com/robimez" ) def rroti(update, context): with open('./rules_of_the_internet.json', encoding="utf8") as f: data = json.load(f) context.bot.send_message( chat_id=update.effective_chat.id,
import threading import os from iotcontrol import iotcontrol from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater from telegram.ext import CommandHandler , CallbackQueryHandler from telegram.ext import MessageHandler, Filters import logging ############################################################################################## darkskyKey = '<Enter dark sky token>' updater = Updater(token='<TELEGRAM TOKEN>') #Insert bot token #required by bot to execute functions see example: https://python-telegram-bot.org/ control = iotcontrol(1234567,darkskyKey,33.8463634,-84.373057) # 1234567 is example admin id : find yours by going to web-api of telegram: https://api.telegram.org/bot<TOKEN>/getUpdates #<TOKEN> is telegram token during bot creation #read: https://zenofall.com/raspberry-pi-telegram-home-automation/ #replace: 33.8463634,-84.373057 by latitude longitude of your location from google maps #we use adminId for special privileges on the bot dispatcher = updater.dispatcher #bot examples: https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples #logging is always good #define logging format and file location
def main(): locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8') conf = confighelper.ConfigHelper(sys.argv[1]) updater = Updater(token=conf.get_anastasia_key()) dispatcher = updater.dispatcher mongoda.MongoDA.init(conf) room = roomcommand.RoomCommand(loghelper.log, conf.path_ics()) todo = todolist.Todo() nudeModule = nude start_handler = CommandHandler('room', room.give_room) joke_handler = CommandHandler('joke', joke.give_joke) blc_handler = CommandHandler('blc', joke.give_blc) todo_handler = CommandHandler('todo', todo.give_todo, pass_args=True) addtodo_handler = CommandHandler('addtodo', todo.give_add_todo, pass_args=True) keskonmange_handler = CommandHandler('keskonmange', new_eat) weather_handler = CommandHandler('weather', weather.give_weather, pass_args=True) airquality_handler = CommandHandler('airquality', airquality.give_airquality, pass_args=True) nude_handler = CommandHandler('nude', nudeModule.get_nude, pass_args=True) chatte_handler = CommandHandler('chatte', joke.get_chatte) help_handler = CommandHandler('help', help.give_credits) fact_handler = CommandHandler('fact', fact.give_fact) citation_handler = CommandHandler('citation', fact.give_citation) chienne_handler = CommandHandler('chienne', joke.get_chienne) kappa_handler = CommandHandler('kappa', joke.send_kappa) callback_handler = CallbackQueryHandler(eat_callback) callback_handler_todo = CallbackQueryHandler(todo.todo_callback) dispatcher.add_handler(start_handler) dispatcher.add_handler(joke_handler) dispatcher.add_handler(blc_handler) dispatcher.add_handler(todo_handler) dispatcher.add_handler(addtodo_handler) dispatcher.add_handler(keskonmange_handler) dispatcher.add_handler(callback_handler, group=0) dispatcher.add_handler(callback_handler_todo, group=1) dispatcher.add_handler(weather_handler) dispatcher.add_handler(airquality_handler) dispatcher.add_handler(nude_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(chatte_handler) dispatcher.add_handler(fact_handler) dispatcher.add_handler(citation_handler) dispatcher.add_handler(chienne_handler) dispatcher.add_handler(kappa_handler) if not conf.get_webhook(): updater.start_polling() else: updater.start_webhook(listen='0.0.0.0', port=int(conf.get_webhook_port()), url_path=conf.get_anastasia_key(), key=conf.get_webhook_private_ssl(), cert=conf.get_webhook_certif(), webhook_url=conf.get_webhook_adress() + ":" + conf.get_webhook_port() + "/" + conf.get_anastasia_key()) updater.start_polling()
from misbot.bunk import bunk, bunk_choose, bunk_input, bunk_calc from misbot.decorators import signed_up, admin from misbot.general import (start, register, credentials, parent_login, delete, cancel, unknown, help_text, tips, error_callback, subscription) from misbot.mis_utils import bunk_lecture, until_x, check_login, check_parent_login, crop_image from misbot.push_notifications import push_message_threaded, get_user_list, delete_threaded from misbot.spider_functions import attendance, results, itinerary, profile from misbot.states import * from misbot.until_func import until, until_eighty from scraper.database import db_session, init_db from scraper.models import Chat, Lecture, Practical, Misc, PushNotification, PushMessage TOKEN = os.environ['TOKEN'] updater = Updater(TOKEN) # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def main(): """Start the bot and use webhook to detect and respond to new messages.""" init_db() dispatcher = updater.dispatcher # Handlers
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler import logging updater = Updater(token="651324863:AAHFpPhxnJSisqWidTlfU9MrgQ8P-uLTJ6s") dispatcher = updater.dispatcher logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def start(bot, update): bot.send_message(chat_id=update.message.chat_id, text="Hola, como estás?") def echo(bot, update): bot.send_message(chat_id=update.message.chat_id, text=update.message.text) def caps(bot, update, args): textCaps = ' '.join(args).upper() bot.send_message(chat_id=update.message.chat_id, text=textCaps) def unknown(bot, update): bot.send_message(chat_id=update.message.chat_id, text="Lo siento, no he entendido el comando.") def setRacoToken(self, token): racoToken = token startHandler = CommandHandler('start', start) capsHandler = CommandHandler('caps', caps, pass_args=True) echoHandler = MessageHandler(Filters.text, echo) unknownHandler = MessageHandler(Filters.command, unknown) dispatcher.add_handler(startHandler) dispatcher.add_handler(capsHandler)
import random import sqlite3 from telegram.error import BadRequest from telegram.ext import Updater, CommandHandler from telegram.ext import dispatcher conn = sqlite3.connect('users.db') users_id = [ 928026036, 923626248, 460729305, 405196888, 375832364, 368778663, 346956156, 228829286 ] updater = Updater("923626248:AAHT1GVNcdDvdUjW6zDYrQ04biRJk4CRfhY", use_context=True) logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") def hello(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text='Que te pasa puta? queres que te la ponga?')
import telegram import config import logging from telegram.ext import Updater, MessageHandler, CommandHandler, Filters import LogicHandler, Parser, Error logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) bot = telegram.Bot(token=config.token) updater = Updater(token=config.token) dispatcher = updater.dispatcher msg_for_comparison = [] # def start(bot, update): # bot.send_message(chat_id=update.message.chat_id, text='Hi! /help if you need more instructions') def parseInput(bot, update): msgText = update.message.text.replace("/parsethis ", "") if (Error.error(msgText)): bot.send_message(chat_id=update.message.chat_id, text="Error in Notation! Try Again!", parse_mode="Markdown") else: predicateFn = LogicHandler.stringToFn(Parser.textToLogic(msgText)) params = Parser.paramsGetter(msgText) res = LogicHandler.getTable(predicateFn, params)
from telegram.ext import Filters, Updater, CommandHandler, InlineQueryHandler, ConversationHandler, RegexHandler, MessageHandler from telegram import InlineQueryResultArticle, InputTextMessageContent, ReplyKeyboardMarkup, ReplyKeyboardRemove, ChatAction from intents import intents from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, String, MetaData CHOOSING_START, SUBSCRIBE, COMPANY, TYPING_REPLY = range(4) '''Reading config details''' config = ConfigParser() config.readfp(open('intents.config')) token = config.get('settings', 'token') typing_time = config.getint('settings', 'typing_time') db_url = config.get('settings', 'DB_URL') print(token) updater = Updater(token=token, use_context=True) dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) meta = MetaData() engine = create_engine(db_url, echo=True) '''Initialising table''' users = Table( 'users', meta, Column('email_id', String, primary_key=True), Column('company_name', String),
def main(): print("Starting bot") global pp, updater, globalsns globalsns = shelve.open(PERSISTENCE_GLOBAL_SNS_FILENAME, writeback=True) # Create the Updater and pass it your bot's token. pp = PicklePersistence(filename=PERSISTENCE_USER_FILENAME, store_user_data=True, store_chat_data=False, on_flush=True) updater = Updater(TELEGRAM_TOKEN, persistence=pp, user_sig_handler=stop_rta_thread) start_rta_update_thread() # Get the dispatcher to register handlers dp = updater.dispatcher updater.dispatcher.add_handler( CommandHandler('start', start, pass_user_data=True)) updater.dispatcher.add_handler( CommandHandler('dist', show_dist, pass_user_data=True)) updater.dispatcher.add_handler( CommandHandler('send', send_stake, pass_user_data=True, pass_args=True)) updater.dispatcher.add_handler( CommandHandler('balance', balance, pass_user_data=True)) updater.dispatcher.add_handler( CommandHandler('donate', donate, pass_user_data=True)) updater.dispatcher.add_handler( CommandHandler('sn', show_sn, pass_user_data=True, pass_args=True)) updater.dispatcher.add_handler( CommandHandler('sample', show_sample, pass_user_data=True, pass_args=True)) updater.dispatcher.add_handler( CommandHandler('height', show_height, pass_user_data=True, pass_args=True)) updater.dispatcher.add_handler( CommandHandler('nodes', show_nodes, pass_user_data=True, pass_args=True)) updater.dispatcher.add_handler( CommandHandler('snodes', show_snodes, pass_user_data=True, pass_args=True)) updater.dispatcher.add_handler( MessageHandler(Filters.text, msg_input, pass_user_data=True)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() print("Bot started") # 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() print("Saving persistence and shutting down") pp.flush() globalsns.close()
from telegram.ext import Updater import twitterbotv2 import emoji #get credentials (api key) from file tgCredentialFile = open("telegram_credentials.txt", "r") creds = tgCredentialFile.readlines() #api key to tg updater = Updater(token=creds[0], use_context=True) dispatcher = updater.dispatcher UpdateDict = {} #function to call twitterupdate that return a list of new followings def formMessage(): #Get dict from twitterbot and loop through keys (influencer handles) and arrays under keys (new followings) _message = "" UpdateDict = twitterbotv2.twitterupdate() if UpdateDict: #check if dict is empty or not, if not empty form message of data, otherwise inform bot user for x, y in UpdateDict.items(): if _message == "": _message = x + " started following:\n" else: _message = "\n\n" + _message + x + " started following:\n" for j in range(len(y)): _message = _message + "www.twitter.com/" + y[j] + "\n" else: _message = "No new follows by influencers that this bot keeps track of!"
"/stop": "Detiene el bot", "/multi_msg": "Manda un argumento a todos los integrantes del grupo", "/chat_id": "Devuelve la id del chat", "/reset": "Reinicia servidor '/reset_help' para mas info", "/read_logs": "Devuelve los ultimos logs, acepta argumentos para realizar un grep", "/write_logs": "Crea un log aceptando un argumento" } host_name = os.popen("hostname").read() route = "/usr/local/src/ResetTelegramGit/" location_logs = "Datos_telegram/logs_telegram.txt" # rebootServers = [] print("Vamos a empezar.") updater = Updater(token='TokendelBot') dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def start(bot, update): write_logs(bot, update, ["/start"]) bot.send_message(chat_id=update.message.chat_id, text="Yo soy un bot, Por favor hablame!") def echo(bot, update): bot.send_message(chat_id=update.message.chat_id, text=update.message.text)
update_handler = CommandHandler('atualizar', update_matches) dispatcher.add_handler(update_handler) menu_handler = CommandHandler('menu', menu_list) dispatcher.add_handler(menu_handler) except Exception as e: print("Método: {}-Erro: {}".format("load_all_dispatcher", str(e))) if (__name__ == '__main__'): try: ACCESS = os.environ["TELEGRAM_SERVER"] TOKEN = os.environ['TELEGRAM_TOKEN'] PORT = int(os.environ.get('PORT', os.environ['TELEGRAM_PORT'])) UPD = Updater(TOKEN) load_all_dispatcher() if (ACCESS == "HEROKU"): HEROKU_URL = os.environ['HEROKU_URL'] UPD.start_webhook(listen='0.0.0.0', port=PORT, url_path=TOKEN) UPD.bot.set_webhook(HEROKU_URL + TOKEN) UPD.idle() else: UPD.start_polling() logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def __init__(self, config_path): self._load_config(config_path) self.updater = Updater(self.config.bot_token) self.handlers = []
return { "token": setting["token"], "proxy": setting["proxy"], "proxy_address": setting["proxy_address"], } raise Exception("setting.json not found.") if __name__ == "__main__": settings = get_settings() if settings["proxy"]: updater = Updater( settings["token"], use_context=True, request_kwargs={ "proxy_url": f"socks5h://{settings['proxy_address']}" }, ) else: updater = Updater(settings["token"], use_context=True) dp = updater.dispatcher dp.add_handler( MessageHandler( filters=(Filters.chat_type.groups & Filters.text & Filters.reply), callback=get_code, )) dp.add_handler(CommandHandler("py", python3, Filters.chat_type.groups)) dp.add_handler(CommandHandler("c", clang, Filters.chat_type.groups)) dp.add_handler(CommandHandler("cpp", cpplang, Filters.chat_type.groups)) dp.add_handler(CommandHandler("mysql", mysql, Filters.chat_type.groups))
class Novellevon: token = People.Storyteller def __init__(self): self.updater = Updater(self.token) dispatcher = self.updater.dispatcher # Create commands actions startHndlr = CommandHandler('start', self.start) pauseHndlr = CommandHandler('pause', self.pause) restartHndlr = CommandHandler('restart', self.restart) continueHndlr = CommandHandler('continue', self.renew) dispatcher.add_handler(startHndlr) dispatcher.add_handler(pauseHndlr) dispatcher.add_handler(restartHndlr) dispatcher.add_handler(continueHndlr) def start(self, bot, update): chatId = update.message.chat_id # print update.message # return 0 annie = Actor(token=People.Annie) dave = Actor(token=People.Dave) annie.say_hello(chat_id=chatId) dave.say_hello(chat_id=chatId) # патамушо нам не нада пока #keyboardButtons = [['/pause']] #keyboardMarkup = ReplyKeyboardMarkup(keyboardButtons) #bot.sendMessage(chat_id=chatId, # text="has started", # reply_markup=keyboardMarkup) def pause(self, bot, update): chatId = update.message.chat_id keyboardButtons = [['/continue'], ['/restart']] keyboardMarkup = ReplyKeyboardMarkup(keyboardButtons) bot.sendMessage(chat_id=chatId, text="has paused", reply_markup=keyboardMarkup) def restart(self, bot, update): chatId = update.message.chat_id keyboardButtons = [['/pause']] keyboardMarkup = ReplyKeyboardMarkup(keyboardButtons) bot.sendMessage(chat_id=chatId, text="has restarted", reply_markup=keyboardMarkup) def renew(self, bot, update): chatId = update.message.chat_id keyboardButtons = [['/pause']] keyboardMarkup = ReplyKeyboardMarkup(keyboardButtons) bot.sendMessage(chat_id=chatId, text="has continued", reply_markup=keyboardMarkup) def listen(self): self.updater.start_polling() def about_myself(self): print(self.api.getMe())
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters last_uploaded_photo = "" def echo(bot, update): global last_uploaded_photo try: chat_id = update.message.chat_id bot_chat = bot.getChat(chat_id=chat_id) if bot_chat['photo']['small_file_id'] != last_uploaded_photo: bot.setChatPhoto(chat_id=chat_id, photo=open("telegram.jpg", "rb")) last_uploaded_photo = bot.getChat( chat_id=chat_id)['photo']['small_file_id'] except Exception as e: print(e) TOKEN = "" updater = Updater(token=TOKEN) dispatcher = updater.dispatcher dispatcher.add_handler(MessageHandler(Filters.all, echo)) dispatcher.add_handler(CommandHandler("start", echo)) updater.start_polling(clean=True)