def run_bot(): parser = ArgumentParser(description='MTG Card Image Fetch Telegram Bot') parser.add_argument('token', type=str, metavar='t', help='The Telegram Bot API Token') parser.add_argument('--level', metavar='l', default='info', choices=[l.lower() for l in logging._nameToLevel]) args = parser.parse_args() logging.basicConfig(level=args.level.upper(), format='%(asctime)s | %(levelname)s: %(message)s', datefmt='%m.%d.%Y %H:%M:%S', handlers=[ logging.StreamHandler(), logging.FileHandler( 'mtgbot_{:%Y_%m_%d_%X}.log'.format( datetime.now())) ]) bot = telepot.DelegatorBot(args.token, [ pave_event_space()( per_inline_from_id(), create_open, InlineHandler, timeout=20), ]) bot.message_loop(run_forever='Listening ...')
def main(): config = resource_filename(__name__, 'configs.yaml') config = yaml.load(open(config).read()) bot = telepot.DelegatorBot(config['token'], [ (per_inline_from_id(), create_open(NoSpoiler, timeout=30)), (per_chat_id(), create_open(NoSpoiler, timeout=2)), ]) bot.message_loop(run_forever='Running ...')
def main(loggingfile, TOKEN): logging.basicConfig(filename=loggingfile + '.log', format='%(asctime)-15s %(message)s') bot = telepot.DelegatorBot(TOKEN, [ pave_event_space()( per_inline_from_id(), create_open, InlineHandler, timeout=1), include_callback_query_chat_id(pave_event_space())( per_chat_id(), create_open, MessageHandler, timeout=1) ]) bot.message_loop(run_forever='Listening ...')
def main(): initLogger() logger.info("Application started...") bot = telepot.DelegatorBot( getToken(), [(per_inline_from_id(), create_open(InlineHandler, timeout=None)), ]) logger.info("Bot registered.") bot.notifyOnMessage(run_forever=True) logger.info("Application closing.")
def main(): # Get the dispatcher to register handlers bot = telepot.DelegatorBot(token, [ (per_inline_from_id(), create_open(HowDoIBot, timeout=30)), (per_chat_id(), create_open(HowDoIBot, timeout=10)), ]) logger.info('Starting bot') # bot.message_loop({'inline_query': on_inline_query, # 'chosen_inline_result': on_chosen_inline_result, # 'chat': on_chat_message}, # run_forever='Listening ...') bot.message_loop(run_forever='Listening ...')
result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) ############################################# # token/bot setup # ############################################# if len(sys.argv) < 3: print("Need a path to a file with valid tokens!") sys.exit(0) token_path = sys.argv[1] try: with open(token_path) as f: TOKEN = f.read().splitlines()[0] except Exception: print("Point me to a proper file!") print(TOKEN) # Initialise the bot bot = telepot.DelegatorBot(TOKEN, [( per_inline_from_id(), create_open(InlineHandler, timeout=30)) ]) print('Listening, shhhh') # run forevs <3 bot.message_loop(run_forever=True)
""" class InlineHandler(telepot.helper.UserHandler): def __init__(self, seed_tuple, timeout): super(InlineHandler, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result']) def on_message(self, msg): flavor = telepot.flavor(msg) if flavor == 'inline_query': query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor) print(self.id, ':', 'Inline Query:', query_id, from_id, query_string) articles = [{'type': 'article', 'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}] self.bot.answerInlineQuery(query_id, articles) print(self.id, ':', 'Answers sent.') elif flavor == 'chosen_inline_result': result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor) print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(InlineHandler, timeout=10)), ]) bot.notifyOnMessage(run_forever=True)
""" class InlineHandler(telepot.helper.InlineUserHandler): def __init__(self, seed_tuple, timeout): super(InlineHandler, self).__init__(seed_tuple, timeout) self._answerer = telepot.helper.Answerer(self.bot) def on_inline_query(self, msg): def compute_answer(): query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query') print(self.id, ':', 'Inline Query:', query_id, from_id, query_string) articles = [{'type': 'article', 'id': 'abc', 'title': query_string, 'message_text': query_string}] return articles self._answerer.answer(msg, compute_answer) def on_chosen_inline_result(self, msg): result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(InlineHandler, timeout=10)), ]) bot.message_loop(run_forever=True)
def __init__(self, seed_tuple, timeout): super(UserHandlerSubclassInlineOnly, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result']) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print('%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance2(msg, flavor=flavor))) def on_close(self, exception): print('%s %d: closed' % (type(self).__name__, self.id)) TOKEN = sys.argv[1] bot = telepot.async.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.messageLoop()) print('Listening ...') loop.run_forever()
'_': lambda msg: True }]) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print '%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance(msg, flavor=flavor)) # Do some simple stuff for every message, to be paired with per_message() def simple_function(seed_tuple): bot, msg, id = seed_tuple print 'Simply print:', msg TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)), (per_application(), create_open(OnlyOneInstance)), (per_message(), call(simple_function)), ]) bot.message_loop(run_forever=True)
# DelegatorBot works wrongly with callback # so we convert callback to ordinary message class DelegatorBotFixed(telepot.DelegatorBot): def handle(self, msg): if "message" in msg: new_msg = { 'chat': msg['message']['chat'], 'date': msg['message']['date'], 'from': msg['from'], 'message_id': msg['message']['message_id'], 'text': msg['data'] } else: new_msg = msg print("mgs=", new_msg) super().handle(new_msg) TOKEN = sys.argv[1] # get token from command-line bot = DelegatorBotFixed(TOKEN, [ pave_event_space()( per_inline_from_id(), create_open, InlineProgroBot, timeout=300), pave_event_space()(per_real_chat_id, create_open, ProgroBot, timeout=300), ]) print('Listening ...') bot.message_loop(run_forever=True)
self._count += 1 text = '%d. %s' % (self._count, query_string) articles = [InlineQueryResultArticle( id='abc', title=text, input_message_content=InputTextMessageContent( message_text=text ) )] return articles self.answerer.answer(msg, compute) def on_chosen_inline_result(self, msg): result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] # get token from command-line bot = telepot.DelegatorBot(TOKEN, [ pave_event_space()( per_inline_from_id(), create_open, QueryCounter, timeout=10), ]) MessageLoop(bot).run_as_thread() while 1: time.sleep(10)
return yes, no def on__expired(self, event): evt = telepot.peel(event) inline_message_id = evt['inline_message_id'] suggested_date = evt['date'] ballot = self._ballots[inline_message_id] text = '%s\nYes: %d\nNo: %d' % ((suggested_date,) + self._count(ballot)) editor = telepot.helper.Editor(self.bot, inline_message_id) editor.editMessageText(text=text, reply_markup=None) del self._ballots[inline_message_id] self.close() def on_close(self, ex): global user_ballots user_ballots[self.id] = self._ballots print('Closing, ballots saved.') TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ intercept_callback_query_origin( pave_event_space())( per_inline_from_id(), create_open, DateCalculator, timeout=10), ]) bot.message_loop(run_forever='Listening ...')
except: query_photo_url = wikipedia.page(f'{query_string}').url try: qlan2 = wikipedia.summary(f'{query_title}', sentences=2,auto_suggest=False, redirect=False) except: qlan2 = wikipedia.summary(f'{query_title}', sentences=2,auto_suggest=True, redirect=True) #url = 'https://images.app.goo.gl/Lax8rhEP3r8uXyy26' #photos = [InlineQueryResultPhoto(id='12345', photo_url=query_photo_url, thumb_url=query_photo_url)] articles = [InlineQueryResultArticle(id='abc',title=f'{query_string}',thumb_url=query_photo_url,input_message_content=InputTextMessageContent(message_text=f'{qlan2}'),)] return articles answerer = telepot.helper.Answerer(msg, compute) def on_chosen_inline_result(msg): result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') TOKEN = "1576421495:AAGoykAN3T4FUysSOK1D4ql8QOq2Dv4tGZ8" # get token from command-line try: bot = telepot.DelegatorBot(TOKEN, [pave_event_space()(per_inline_from_id(), create_open, timeout=20),]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) MessageLoop(bot, {'inline_query': on_inline_query,'chosen_inline_result': on_chosen_inline_result,'chat':on_chat_message,}).run_as_thread() except: pass print('Listening ...') while 1: time.sleep(10)
inline_message_id = evt['inline_message_id'] suggested_date = evt['date'] ballot = self._ballots[inline_message_id] text = '%s\nYes: %d\nNo: %d' % ( (suggested_date, ) + self._count(ballot)) editor = telepot.helper.Editor(self.bot, inline_message_id) editor.editMessageText(text=text, reply_markup=None) del self._ballots[inline_message_id] self.close() def on_close(self, ex): global user_ballots user_ballots[self.id] = self._ballots print('Closing, ballots saved.') TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ intercept_callback_query_origin(pave_event_space())( per_inline_from_id(), create_open, DateCalculator, timeout=10), ]) MessageLoop(bot).run_as_thread() print('Listening ...') while 1: time.sleep(10)
def __init__(self, seed_tuple): super(OneInstanceOnly, self).__init__(seed_tuple, capture=[{'_': lambda msg: True}]) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print '%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance(msg, flavor=flavor)) # Do some simple stuff for every message, to be paired with per_message() def simple_function(seed_tuple): bot, msg, id = seed_tuple print 'Simply print:', msg TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(InlineUserHandlerSubclass, timeout=10)), (per_application(), create_open(OneInstanceOnly)), (per_message(), call(simple_function)), ]) bot.message_loop(run_forever=True)
def main(): bot = telepot.DelegatorBot(load_key("telegram"), [ pave_event_space()( per_inline_from_id(), create_open, GifBot, timeout=10), ]) bot.message_loop(run_forever='Listening ...')
def on_close(self, exception): print '%s %d: closed' % (type(self).__name__, self.id) # Captures inline-related messages from a user, to be paired with per_inline_from_id() class UserHandlerSubclassInlineOnly(telepot.helper.UserHandler): def __init__(self, seed_tuple, timeout): super(UserHandlerSubclassInlineOnly, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result']) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print '%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance(msg, flavor=flavor)) def on_close(self, exception): print '%s %d: closed' % (type(self).__name__, self.id) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)), ]) bot.notifyOnMessage(run_forever=True)
'message_text': 'ಠ_ಠ'}] elif query_string == 'lenny': articles = [{'type': 'article', 'id': 'lenny', 'title': '( ͡° ͜ʖ ͡°)', 'message_text': '( ͡° ͜ʖ ͡°)'}] else: articles = [{'type': 'article', 'id': 'error', 'title': 'Text smiley is not found', 'message_text': 'Text smiley is not found'}] print(self.id, ':', 'Inline Query:', query_id, from_id, query_string) return articles self.answerer.answer(msg, compute_answer) def on_chosen_inline_result(self, msg): from pprint import pprint pprint(msg) result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) bot = telepot.DelegatorBot(config.token, [ pave_event_space()( per_inline_from_id(), create_open, InlineHandler, timeout=100000), ]) bot.message_loop(run_forever='Listening ...')