def __init__(self, token, owner_id): self._owner_id = owner_id self._seen = set() self._store = UnreadStore() super(ChatBox, self).__init__(token, [ # Here is a delegate to specially handle owner commands. (per_chat_id_in([owner_id]), create_open(OwnerHandler, 20, self._store)), # Only one MessageSaver is ever spawned for entire application. (per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])), # For senders never seen before, send him a welcome message. (self._is_newcomer, call(self._send_welcome)), ])
def __init__(self, token, owner_id): self._owner_id = owner_id self._seen = set() self._store = UnreadStore() super(ChatBox, self).__init__( token, [ # Here is a delegate to specially handle owner commands. (per_chat_id_in( [owner_id]), create_open(OwnerHandler, 20, self._store)), # Only one MessageSaver is ever spawned for entire application. (per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])), # For senders never seen before, send him a welcome message. (self._is_newcomer, call(self._send_welcome)), ])
def __init__(self, configuration): self._admins_telegram_ids = configuration.admins_telegram_ids self._delegator_bot = telepot.aio.DelegatorBot( configuration.token, [ # If the bot isn't chatting with an admin, skip, so for this # chat will be used another handler, not AdminHandler. (per_from_id_in(self._admins_telegram_ids), create_open( AdminHandler, timeout=60, )), # If the bot is chatting with an admin, skip, so for this chat # will be used another handler, not StrangerHandler. (per_from_id_except(self._admins_telegram_ids), create_open( StrangerHandler, timeout=60, )), ], )
def __init__(self): self.token = open(config.TOKEN_FILE).read().strip() self._seen = set() super(BotManager, self).__init__(self.token, [ pave_event_space()( per_from_id_in(config.WHITELIST) if config.WHITELIST else per_from_id(), create_open, chatbot.ChatBot, None, timeout=10 * 60 ), ( per_application(), create_open(adminmonitor.AdminMonitor, config.ADMINS_LIST) ), ])
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', default=join('config', 'prod.yml')) args = parser.parse_args() with open(args.config) as config_file: config = yaml.load(config_file.read()) # Is it main app or test app is_main = config['pockebot_is_main'] # Got Telegram bot access token # config_manager = db.PockebotDBSlave(config) # token = config_manager.get_bot_token() token = config['telegram_token'] bot = telepot.aio.DelegatorBot(token, [ (per_from_id(), create_open(PocketBot, timeout=60, is_main=is_main, config=config)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
query_id, text='You have already voted %s' % self._votes[from_id]) else: await self.bot.answerCallbackQuery(query_id, text='Ok') self._votes[from_id] = query_data if len(self._votes) >= self._members_count: await self._editor.editMessageReplyMarkup(reply_markup=None) await self.sender.sendMessage('Everyone has voted. Thank you.') await self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes()) async def on_timeout(self, exception): await self._editor.editMessageReplyMarkup(reply_markup=None) await self.sender.sendMessage('Time is up.') await self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes()) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(types=['group']), create_open(VoteCounter, timeout=20)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
async def on_edited_chat_message(self, msg): pass TOKEN = sys.argv[1] # get token from command-line # global variables server_used = False run_args = { 'user': sys.argv[2], 'pass': sys.argv[3], 'step': sys.argv[4], 'host': sys.argv[5], 'port': sys.argv[6], 'gkey': sys.argv[7] } users = {} whitelist = [] # add here your telegram id wait_time = 600 load_time = 120 bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(PokeMap, timeout=3600)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
class TestClass(): def __init__(self): print('Iniciando test') @asyncio.coroutine def test(self): while True: logger = logging.getLogger('simple_example') logger.debug('Test') #print ('TEST') yield from asyncio.sleep(2) bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MessageCounter, timeout=10)), ]) logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger
def __init__(self, seed_tuple, timeout): super(MessageCounter, self).__init__(seed_tuple, timeout) self._count = 0 @asyncio.coroutine def on_chat_message(self, msg): self._count += 1 yield from self.sender.sendMessage(self._count) TOKEN = sys.argv[1] PORT = int(sys.argv[2]) URL = sys.argv[3] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MessageCounter, timeout=10)), ]) update_queue = asyncio.Queue() # channel between web app and bot @asyncio.coroutine def webhook(request): data = yield from request.text() yield from update_queue.put(data) # pass update to bot return web.Response(body='OK'.encode('utf-8')) @asyncio.coroutine def init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/abc', webhook) app.router.add_route('POST', '/abc', webhook)
super(InlineHandler, self).__init__(seed_tuple, timeout) 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.aio.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(InlineHandler, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
guess = int(msg['text']) except ValueError: await self.sender.sendMessage('Give me a number, please.') return # check the guess against the answer ... if guess != self._answer: # give a descriptive hint hint = self._hint(self._answer, guess) await self.sender.sendMessage(hint) else: await self.sender.sendMessage('Correct!') self.close() async def on_close(self, exception): if isinstance(exception, telepot.exception.WaitTooLong): await self.sender.sendMessage('Game expired. The answer is %d' % self._answer) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Player, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
except ValueError: await self.sender.sendMessage('Give me a number, please.') return # check the guess against the answer ... if guess != self._answer: # give a descriptive hint hint = self._hint(self._answer, guess) await self.sender.sendMessage(hint) else: await self.sender.sendMessage('Correct!') self.close() async def on_close(self, exception): if isinstance(exception, telepot.exception.WaitTooLong): await self.sender.sendMessage('Game expired. The answer is %d' % self._answer) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Player, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') if from_id in self._votes: await self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % self._votes[from_id]) else: await self.bot.answerCallbackQuery(query_id, text='Ok') self._votes[from_id] = query_data if len(self._votes) >= self._members_count: await self._editor.editMessageReplyMarkup(reply_markup=None) await self.sender.sendMessage('Everyone has voted. Thank you.') await self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes()) async def on_timeout(self, exception): await self._editor.editMessageReplyMarkup(reply_markup=None) await self.sender.sendMessage('Time is up.') await self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes()) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(types=['group']), create_open(VoteCounter, timeout=20)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
if query_data == 'yes': # hide inline keyboard await self._editor.editMessageReplyMarkup(reply_markup=None) await self.sender.sendMessage('Thank you!') self.close() else: await self.bot.answerCallbackQuery( query_id, text='Ok. But I am going to keep asking.') # hide inline keyboard await self._editor.editMessageReplyMarkup(reply_markup=None) self._count += 1 sent = await self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self._keyboard) self._editor = telepot.aio.helper.Editor(self.bot, sent) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(types=['private']), create_open(Lover, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
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.aio.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(InlineHandler, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
async def on_callback_query(self, msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') if query_data == 'yes': # hide inline keyboard await self._editor.editMessageReplyMarkup(reply_markup=None) await self.sender.sendMessage('Thank you!') self.close() else: await self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.') # hide inline keyboard await self._editor.editMessageReplyMarkup(reply_markup=None) self._count += 1 sent = await self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self._keyboard) self._editor = telepot.aio.helper.Editor(self.bot, sent) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(types=['private']), create_open(Lover, timeout=10)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
# creating the bot TOKEN = '244035013:AAHXbdprTeisw3hAUWX7VJehWkThR3WwIzk' # bot's own token # DelegatorBot is a factory # # it constructs a new bot, # if the bot with the same seed(identifier, per_char_id()) doesn't exist # and seed is hashable # # it helps to avoid blocking while listening to the different chats # # if no message is captured after TIME seconds, # delegate is destroyed # # more in the documentation: # https://github.com/nickoala/telepot/blob/master/REFERENCE.md#telepot-DelegatorBot TIME = 10 bot = telepot.aio.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MessageHandler, timeout=TIME)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening...') loop.run_forever()
if content_type != 'text': return text = msg['text'] date_string = self._suggested_date.strftime('%A, %Y-%m-%d') if text == 'Decided': THUMB_UP = u'\U0001f44d\U0001f3fb' await self._suggestion_editor.editMessageText(date_string + '\n' + THUMB_UP + "Let's meet on this day.") else: CROSS = u'\u274c' await self._suggestion_editor.editMessageText(date_string + '\n' + CROSS + "Let me find another day.") # Ignore group messages def on_edited_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg, flavor='edited_chat') print('Edited chat:', content_type, chat_type, chat_id) TOKEN = sys.argv[1] bot = telepot.aio.DelegatorBot(TOKEN, [ (per_from_id(), create_open(DateCalculator, timeout=20)) ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()