class SarcasmBot(object): instance = None def __init__(self): assert SarcasmBot.instance is None SarcasmBot.instance = self self.bot = None self.loop = aio.get_event_loop() self.msg_loop = None def start(self, token): self.bot = telepot.aio.DelegatorBot(token, [ include_callback_query_chat_id(pave_event_space())( per_chat_id(), create_open, SarcasmUser, timeout=10), ]) self.msg_loop = MessageLoop(self.bot) self.loop.create_task(MessageLoop(self.bot).run_forever()) self.loop.run_forever() def stop(self): SarcasmBot.instance = None if self.msg_loop: self.msg_loop.cancel() self.msg_loop = None def __enter__(self): return self def __exit__(self, type, value, tb): self.stop()
class ShoppingBot(object): instance = None def __init__(self, verbose=False): assert ShoppingBot.instance is None ShoppingBot.instance = self self.verbose = verbose self.bot = None self.loop = aio.get_event_loop() self.msg_loop = None self.callbacks = {} def start(self, token): self.bot = telepot.aio.DelegatorBot(token, [ include_callback_query_chat_id(pave_event_space())( per_chat_id(), create_open, ShoppingUser, timeout=10), ]) self.msg_loop = MessageLoop(self.bot) self.loop.create_task(self.msg_loop.run_forever()) self.loop.run_forever() def stop(self): ShoppingBot.instance = None if self.msg_loop: self.msg_loop.cancel() self.msg_loop = None @classmethod def is_verbose(cls): return cls.instance.verbose @classmethod def add_callback(cls, event, cb): assert event in ('cmd', 'add-product', 'flag-product', 'end') cls.instance.callbacks[event] = cls.instance.callbacks.get(event, []) cls.instance.callbacks[event].append(cb) @classmethod async def trigger(cls, event, user, *args, **kwargs): assert event in ('cmd', 'add-product', 'flag-product', 'end') result = True for cb in cls.instance.callbacks.get(event, []): cur = await cb(cls.instance.bot, user, *args, **kwargs) result = result & (cur is None or cur) if result is False: return False return result def __enter__(self): return self def __exit__(self, type, value, tb): self.stop()
def start(self, token): self.bot = telepot.aio.DelegatorBot(token, [ include_callback_query_chat_id(pave_event_space())( per_chat_id(), create_open, SarcasmUser, timeout=10), ]) self.msg_loop = MessageLoop(self.bot) self.loop.create_task(MessageLoop(self.bot).run_forever()) self.loop.run_forever()
def run_async(self, bot_key, bot_url): """Start the bot using asyncio.""" # Telegram served interface, imported here to avoid the cration # of a main loop when importing the current module (bot.py) import telepot from telepot.aio.loop import MessageLoop logging.info('Starting async bot') self.bot = telepot.aio.Bot(bot_key) handlers = { 'chat': self.dispatch, } # Generate a security token self.sec_tok = secrets.token_urlsafe(25) self.url = bot_url app = web.Application() app.router.add_get('/api/{token}/set/todo/{lid}', self.web_set_todo) app.router.add_get('/api/{token}/wlb/{bid}', self.web_wlb) app.router.add_get('/api/{token}/blb/{bid}', self.web_blb) app.router.add_get('/api/{token}/lsl/{bid}', self.web_lsl) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(self.bot, handlers).run_forever()) web.run_app(app)
def _initialise(bot): if not _telesync_config(bot): return if not bot.memory.exists(['telesync']): bot.memory.set_by_path(['telesync'], {'ho2tg': {}, 'tg2ho': {}}) bot.memory.save() if not bot.memory.exists(['profilesync']): bot.memory.set_by_path(['profilesync'], {'ho2tg': {}, 'tg2ho': {}}) bot.memory.save() global client_session global tg_bot global tg_loop client_session = aiohttp.ClientSession() tg_bot = TelegramBot(bot) tg_bot.set_on_message_callback(tg_on_message) tg_bot.set_on_photo_callback(tg_on_photo) tg_bot.set_on_sticker_callback(tg_on_sticker) tg_bot.set_on_user_join_callback(tg_on_user_join) tg_bot.set_on_user_leave_callback(tg_on_user_leave) tg_bot.set_on_location_share_callback(tg_on_location_share) tg_bot.set_on_supergroup_upgrade_callback(tg_on_supergroup_upgrade) tg_bot.add_command("/whoami", tg_command_whoami) tg_bot.add_command("/whereami", tg_command_whereami) tg_bot.add_command("/setsyncho", tg_command_set_sync_ho) tg_bot.add_command("/clearsyncho", tg_command_clear_sync_ho) tg_bot.add_command("/addadmin", tg_command_add_bot_admin) tg_bot.add_command("/removeadmin", tg_command_remove_bot_admin) tg_bot.add_command("/syncprofile", tg_command_sync_profile) tg_bot.add_command("/unsyncprofile", tg_command_unsync_profile) tg_bot.add_command("/getme", tg_command_get_me) tg_loop = MessageLoop(tg_bot) plugins.start_asyncio_task(tg_loop.run_forever()) plugins.start_asyncio_task(tg_bot.setup_bot_info()) plugins.register_admin_command(["telesync"]) plugins.register_user_command(["syncprofile"]) plugins.register_handler(_on_membership_change, type="membership")
def main(): """ Set up the `event_loop`. """ loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot, handle).run_forever()) print('Running like crazy yo!') loop.run_forever()
def main(): bot = telepot.aio.DelegatorBot(TELEGRAM_TOKEN, [ pave_event_space()( per_chat_id(), create_open, MessageCounter, timeout=10), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) loop.run_forever()
def main(): logging.basicConfig( filename=settings.LOG_FILE, level=settings.LOG_LEVEL, format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') #loop.create_task(MessageLoop(bot).run_forever()) asyncio.ensure_future( MessageLoop(bot, handle).run_forever(relax=0.01, offset=-1)) print('Messge Listening ...') loop.run_forever()
def main(): api_token = os.environ.get('TELEPOT_API_TOKEN') if api_token is None: sys.exit('Please set environment "TELEPOT_API_TOKEN"') global bot bot = telepot.aio.Bot(api_token) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot, handle).run_forever()) print('Listening...') loop.run_forever()
def main(): instagram_bot = InstagramAPI(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD) instagram_bot.login() bot = telepot.aio.DelegatorBot(config('TOKEN'), [ include_callback_query_chat_id(pave_event_space())( per_chat_id(types=['private']), create_open, GeneratePostChatHandler, timeout=10), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) print('Listening ...') loop.run_forever()
def main(token): bot = telepot.aio.DelegatorBot(token, [ include_callback_query_chat_id(pave_event_space())( per_chat_id(types=['private']), create_open, LentaReader, timeout=10), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) print('Listening ...') loop.run_forever()
def main(config, state): logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() bot = telepot.aio.Bot(config['token']) alert_bot = AlertBot(bot, loop, config['valid_users'], state) email_handler = UnifiAlertMessage(alert_bot) # create smtpd task loop.create_task( email_handler.smtpd_main(config.get('smtp_listen', '0.0.0.0'), config.get('smtp_port', 8025))) # create bot task loop.create_task(MessageLoop(bot, alert_bot.handle).run_forever()) logging.info("Starting Bot and smtpd") loop.run_forever()
def run(cls): token = os.environ['token'] # token = botconfig.token() bot = telepot.aio.DelegatorBot(token, [ pave_event_space()( per_chat_id(), create_open, cls, timeout=cls.timeout), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) print('Listening ...') loop.run_forever()
async def main(token): ''' Start the bot main loop Args: token: token of the bot created with BotFather ''' bot = Bot(token) coup_bot = CoupBot(bot, (await bot.getMe())['username']) loop = asyncio.get_event_loop() loop.create_task( MessageLoop( coup_bot.bot, routes(coup_bot) ).run_forever() )
def main(args=None): """The main routine""" if args is None: args = sys.argv[1:] bot = telepot.aio.DelegatorBot(TOKEN, [ include_callback_query_chat_id(pave_event_space())( per_chat_id(types=["group"]), create_open, DudoHandler, timeout=300), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) loop.run_forever()
async def main(): global tg_bot # get environment variables TOKEN: str = os.environ['BOT_TOKEN'] tg_bot = telepot.aio.Bot(TOKEN) loop = asyncio.get_event_loop() await postgres_connect() await postgres_create_tables() loop.create_task( MessageLoop(tg_bot, { 'chat': on_chat_message }).run_forever()) log.info('Listening for messages in Telegram...')
def listen(self) -> None: """ Activates the bot by running it in a never ending asynchronous loop """ # Creates an event loop global loop loop = asyncio.get_event_loop() # Changes its task factory to use the async context provided by aiotask_context loop.set_task_factory(_context.copying_task_factory) # Creates the forever running bot listening function as task loop.create_task(MessageLoop(self._bot).run_forever(timeout=None)) # Create the startup as a separated task loop.create_task(self.schedule_startup()) # Start the event loop to never end (of itself) loop.run_forever()
def main(config, state): logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() bot = telepot.aio.Bot(config['token']) alert_bot = AlertBot(bot, loop, config['valid_users'], state) email_handler = UnifiAlertMessage(alert_bot) smtp_listen = config.get('smtp_listen', '0.0.0.0') smtp_port = config.get('smtp_port', 8025) # create smtpd task loop.create_task(email_handler.smtpd_main(smtp_listen, smtp_port)) # create the ftpd task ftp_user = config['ftp']['user'] ftp_password = config['ftp']['password'] ftp_port = config['ftp']['port'] ftp_dir = tempfile.mkdtemp() loop.run_in_executor(None, ftp.run_ftpd, '0.0.0.0', ftp_port, alert_bot, ftp_user, ftp_password, ftp_dir) # create bot task loop.create_task(MessageLoop(bot, alert_bot.handle).run_forever()) logging.info("Starting Bot and smtpd") loop.run_forever()
def main(): # ТУТ БУДЕТ НАШ КОД РАБОТЫ С БАЗОЙ ДАННЫХ # КОД ДАЛЬНЕЙШИХ ПРИМЕРОВ ВСТАВЛЯТЬ В ЭТО МЕСТО # Не забываем закрыть соединение с базой данных TOKEN = sys.argv[1] # get token from command-line bot = telepot.aio.DelegatorBot(TOKEN, [ pave_event_space()( per_chat_id(), create_open, AttendanceStarter, timeout=3), pave_event_space()( per_callback_query_origin(), create_open, Attendance, timeout=60), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) print('Listening ...') loop.run_forever()
await bot.answerCallbackQuery(query_id, text='Notification at top of screen') elif data == 'alert': await bot.answerCallbackQuery(query_id, text='Alert!', show_alert=True) elif data == 'edit': global message_with_inline_keyboard if message_with_inline_keyboard: msg_idf = telepot.message_identifier(message_with_inline_keyboard) await bot.editMessageText(msg_idf, 'NEW MESSAGE HERE!!!!!') else: await bot.answerCallbackQuery(query_id, text='No previous message to edit') TOKEN = config.token bot = telepot.aio.Bot(TOKEN) answerer = telepot.aio.helper.Answerer(bot) loop = asyncio.get_event_loop() loop.create_task( MessageLoop(bot, { 'chat': on_chat_message, 'callback_query': on_callback_query, }).run_forever()) print('Listening ...') #=================================================== loop.run_forever()
# db = shelve.open("session.db", "c", writeback=True) atexit.register(lambda: k.saveBrain('brain.sav')) k = Kernel() # sessionStore=db) k.learn("startup.xml") k.respond("load aiml b") class MessageKiller(telepot.aio.helper.ChatHandler): def __init__(self, *args, **kwargs): super(MessageKiller, self).__init__(*args, **kwargs) async def on_chat_message(self, msg): print("Message text ", msg["text"]) res = k.respond(msg["text"]).replace(" ", " ").replace(" ", " ") print("Response ", res) await self.sender.sendMessage(res) TOKEN = "here_goes_bot_token" bot = telepot.aio.DelegatorBot(TOKEN, [ pave_event_space()(per_chat_id(), create_open, MessageKiller, timeout=30), ]) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot).run_forever()) print('Listening ...') loop.run_forever()
switch_pm_parameter='Optional_start_parameter') else: return dict(results=results) answerer.answer(msg, compute) def on_chosen_inline_result(msg): result_id, from_id, query_string = telepot.glance( msg, flavor='chosen_inline_result') print('Chosen Inline Result:', result_id, from_id, query_string) TOKEN = config.TOKEN # get token from command-line bot = telepot.aio.Bot(TOKEN) answerer = telepot.aio.helper.Answerer(bot) loop = asyncio.get_event_loop() loop.create_task( MessageLoop( bot, { 'chat': on_chat_message, 'callback_query': on_callback_query, 'inline_query': on_inline_query, 'chosen_inline_result': on_chosen_inline_result }).run_forever()) print('Listening ...') loop.run_forever()
await bot.sendMessage( chat_id, f'Simulating {amount} ZAR for {coin_type} using {zar_exchange}...') coin_data = COIN_MAP[zar_exchange][coin_type] message = arbitrage(amount, **coin_data)['summary'] # import pdb; pdb.set_trace() await bot.sendMessage(chat_id, message, reply_to_message_id=msg['message_id']) else: print('No idea') getcontext().prec = 8 # Set Decimal context. load_dotenv('.env') # Load environment TOKEN = os.environ.get('TELEGRAM_TOKEN') # get token from environment bot = telepot.aio.Bot(TOKEN) answerer = telepot.aio.helper.Answerer(bot) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot, { 'chat': on_chat_message, }).run_forever()) print('Listening ...') loop.run_forever()
def start_message_loop(**kwargs): loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot2).run_forever()) print('Listening ...') loop.run_forever()
def main(): message_with_inline_keyboard = None async def send_media_instaloader(): while True: session = config.Session() try: pics_to_send = session.query(InstagramImageNoRss).filter( InstagramImageNoRss.sended == False).all() for pic_to_send in pics_to_send: with open(pic_to_send.local_path, 'rb') as mediaf: for chat_id in [ x.chat_id for x in session.query(Chat).filter( Chat.admin == True).all() ]: if pic_to_send.local_path.endswith('.jpg'): logging.info('sending photo') await bot.sendPhoto( chat_id=chat_id, photo=mediaf, caption="/{} from instaloader".format( pic_to_send.username)) logging.info('sended photo') elif pic_to_send.local_path.endswith('.mp4'): logging.info('sending video') await bot.sendVideo( chat_id=chat_id, video=mediaf, caption="/{} index={} from instaloader". format(pic_to_send.username, pic_to_send.text_data)) logging.info('sended video') else: await bot.sendMessage( chat_id=chat_id, text= 'Not understand type please debug me. {}'. format(pic_to_send)) continue if pic_to_send.text_data is not None and len( pic_to_send.text_data) > 0: await bot.sendMessage( chat_id=chat_id, text= '/{} index={} from instaloader with text {}' .format(pic_to_send.username, pic_to_send.publication_index, pic_to_send.text_data)) if config.SEND_JSON_DATA and pic_to_send.json_data is not None and len( pic_to_send.json_data) > 0: await bot.sendMessage( chat_id=chat_id, text= '/{} index={}from instaloader with json data\n{}' .format( pic_to_send.username, pic_to_send.text_data, json.dumps(json.loads( pic_to_send.json_data), indent=4))[:4000]) if pic_to_send.geolocation_data is not None and len( pic_to_send.geolocation_data) > 0: geo = pic_to_send.geolocation_data await bot.sendMessage( chat_id=chat_id, text= '/{} from instaloader with geolocation data\n{}' .format(pic_to_send.username, geo)) geo_parsed = re.search( 'http(s)?:\/\/maps.google.com\/maps\?q=(?P<longitude>(\d|\.)+)\,(?P<latitude>(\d|\.)+)&.*', geo) if geo_parsed: longitude = geo_parsed.group('longitude') latitude = geo_parsed.group('latitude') for zoom in range(0, 18, 3): current_url = 'https://static-maps.yandex.ru/1.x/?ll={},{}&size=450,450&z={}&l=map&pt={},{}'.format( latitude, longitude, zoom, latitude, longitude) current_tmp_filename = os.path.join( tempfile._get_default_tempdir(), next(tempfile._get_candidate_names( ))) await Utils.download( current_url, path=current_tmp_filename) with open(current_tmp_filename, 'rb') as cf: await bot.sendPhoto( chat_id=chat_id, photo=cf, caption= '/{} with geolocation at {}'. format(pic_to_send.username, zoom)) os.remove(current_tmp_filename) await asyncio.sleep(.2) if pic_to_send.comments_data is not None and len( pic_to_send.comments_data): for comment in json.loads( pic_to_send.comments_data): await bot.sendMessage( chat_id=chat_id, text= '/{} комментарий от {} запощен в {} с текстом:\n{}' .format( pic_to_send.username, comment['owner']['username'], datetime.datetime.fromtimestamp( int(comment['created_at']) ).strftime('%Y-%m-%d %H:%M:%S'), comment['text'])) pic_to_send.sended = True session.add(pic_to_send) try: session.commit() except Exception as e: logging.exception(e) session.rollback() except Exception as e: logging.exception(e) for chat_id in [ x.chat_id for x in session.query(Chat).filter( Chat.admin == True).all() ]: await bot.sendMessage(chat_id=chat_id, text='Exception {} with {}'.format( str(e), traceback.format_exc())) finally: session.close() await asyncio.sleep(config.TIME_SLEEP_SENDER) async def send_pictures_rss(): while True: session = config.Session() try: pics_to_send = session.query(InstgaramImageRss).filter( InstgaramImageRss.sended == False).all() for pic_to_send in pics_to_send: with open(pic_to_send.local_path, 'rb') as picf: for chat_id in [ x.chat_id for x in session.query(Chat).filter( Chat.admin == True).all() ]: current_text = '/{} from RSS feed with text: {} '.format( pic_to_send.username, pic_to_send.summary) short_text = '/{} from RSS feed photo'.format( pic_to_send.username) await bot.sendPhoto(chat_id=chat_id, photo=picf, caption=short_text) await bot.sendMessage(chat_id=chat_id, text=current_text) pic_to_send.sended = True session.add(pic_to_send) try: session.commit() except Exception as e: logging.exception(e) session.rollback() except Exception as e: logging.exception(e) for chat_id in [ x.chat_id for x in session.query(Chat).filter( Chat.admin == True).all() ]: await bot.sendMessage(chat_id=chat_id, text='Exception {} with {}'.format( str(e), traceback.format_exc())) finally: session.close() await asyncio.sleep(config.TIME_SLEEP_SENDER) async def on_chat_message(msg): session = config.Session() try: content_type, chat_type, chat_id = telepot.glance(msg) # print('Chat:', content_type, chat_type, chat_id) if content_type != 'text': return command = msg['text'][:].lower() if 'text' in msg and msg['text'] == '/start': new_chat_info = session.query(Chat).filter( Chat.chat_id == chat_id).first() if new_chat_info is None: new_chat_info = Chat(chat_id=chat_id, admin=False, tg_ans=str(msg)) await bot.sendMessage(chat_id, u'Шо?! Новый пользователь?!') else: await bot.sendMessage(chat_id, u'А я тебя уже знаю') session.add(new_chat_info) try: session.commit() except Exception as e: logging.exception(e) session.rollback() elif command.startswith('/admin'): passw = re.search('\/admin\s+(?P<passw>\w+)', msg['text']) if passw and passw.group('passw') == config.BOT_ADMIN_PASSWORD: current_chat_info = session.query(Chat).filter( Chat.chat_id == chat_id).first() current_chat_info.admin = True session.add(current_chat_info) try: session.commit() except Exception as e: session.rollback() await bot.sendMessage(chat_id, u'Слушаю и повинуюсь, хозяин') else: await bot.sendMessage( chat_id, u'ЭЭЭ ТЫ КТО ТАКОЙ? ДАВАЙ ДО СВИДАНИЯ!') elif command.startswith('/subscriptions') and session.query( Chat).filter(Chat.chat_id == chat_id and Chat.admin == True): is_succ = session.query(Chat).filter( and_(Chat.chat_id == chat_id, Chat.admin == True)).all() if not is_succ: return current_message = '' for subscription in session.query(InstagramSubscription).all(): if len(current_message) > 200: current_message += ' ' + str(subscription.username) await bot.sendMessage(chat_id, str(current_message)) else: current_message += ' ' + str(subscription.username) else: is_succ = session.query(Chat).filter( and_(Chat.chat_id == chat_id, Chat.admin == True)).all() if command.startswith('/'): command = command[1:] infomation_about_user = await InstagramFeedParserRSS.get_info( command) if infomation_about_user is None: await bot.sendMessage( chat_id, "Проблема с пользователем {} его rss-лента не парсится" .format(command)) elif is_succ is not None and len(is_succ) > 0: await bot.sendMessage(chat_id, infomation_about_user) markup = InlineKeyboardMarkup(inline_keyboard=[ [ InlineKeyboardButton(text='подписаться', callback_data=json.dumps( { 'action': 'subscribe', 'username': command })) ], [ InlineKeyboardButton( text='отписаться', callback_data=json.dumps({ 'action': 'unsubscribe', 'username': command })) ], [ InlineKeyboardButton( text='прислать последние 3 фото RSS ленты', callback_data=json.dumps({ 'action': 'last', 'username': command })) ], [ InlineKeyboardButton( text='прислать все фото, что есть RSS', callback_data=json.dumps({ 'action': 'all', 'username': command })) ], [ InlineKeyboardButton( text='прислать последние 3 фото Instaloader', callback_data=json.dumps({ 'action': 'last', 'username': command })) ], [ InlineKeyboardButton( text='прислать все фото, что есть Instaloader', callback_data=json.dumps({ 'action': 'all', 'username': command })) ], ]) global message_with_inline_keyboard message_with_inline_keyboard = await bot.sendMessage( chat_id, 'что прикажете?', reply_markup=markup) else: await bot.sendMessage(chat_id, 'Вы не администратор. Вам нельзя.') except Exception as e: logging.exception(e) for chat_id in [ x.chat_id for x in session.query(Chat).filter( Chat.admin == True).all() ]: await bot.sendMessage(chat_id=chat_id, text='Exception {} with {}'.format( str(e), traceback.format_exc())) finally: session.close() async def on_callback_query(msg): query_id, from_id, data = telepot.glance(msg, flavor='callback_query') data = json.loads(data) session = config.Session() try: subscriptions = session.query(InstagramSubscription).filter( InstagramSubscription.username == data['username']).all() if subscriptions is None or len(subscriptions) == 0: current_subscription = InstagramSubscription() else: current_subscription = subscriptions[0] current_subscription.username = data['username'] if data['action'] == 'subscribe': current_subscription.subscribed = True session.add(current_subscription) await bot.sendMessage( from_id, 'subscribed to {}'.format(data['username'])) try: session.commit() except Exception as e: logging.exception(e) session.rollback() elif data['action'] == 'unsubscribe': current_subscription.subscribed = False await bot.sendMessage( from_id, 'unbscribed from {}'.format(data['username'])) try: session.commit() except Exception as e: logging.exception(e) session.rollback() elif data['action'] == 'last_rss': photos = session.query(InstgaramImageRss).filter( InstgaramImageRss.username == data['username']).order_by( desc(InstgaramImageRss.published)).limit(3).all() await send_rss_photos(from_id, photos, session) elif data['action'] == 'all_rss': photos = session.query(InstgaramImageRss).filter( InstgaramImageRss.username == data['username']).order_by( InstgaramImageRss.published).all() await send_rss_photos(from_id, photos, session) except Exception as e: logging.exception(e) for chat_id in [ x.chat_id for x in session.query(Chat).filter( Chat.admin == True).all() ]: await bot.sendMessage(chat_id=chat_id, text='Exception {} with {}'.format( str(e), traceback.format_exc())) finally: session.close() async def send_rss_photos(from_id, photos, session): if photos is None or len(photos) == 0: await bot.sendMessage(from_id, 'Нет фото') else: for photo in photos: with open(photo.local_path, 'rb') as pf: await bot.sendPhoto(chat_id=from_id, photo=pf, caption=photo.summary) await bot.sendMessage(chat_id=from_id, text=photo.summary) photo.sended = True session.add(photo) try: session.commit() except Exception as e: session.rollback() def on_chosen_inline_result(msg): result_id, from_id, query_string = telepot.glance( msg, flavor='chosen_inline_result') return rss_parser = InstagramFeedParserRSS.InstagramRssParser() bot = telepot.aio.Bot(TOKEN) answerer = telepot.aio.helper.Answerer(bot) loop = asyncio.get_event_loop() loop.create_task( MessageLoop( bot, { 'chat': on_chat_message, 'callback_query': on_callback_query, 'chosen_inline_result': on_chosen_inline_result }).run_forever()) loop.create_task(send_pictures_rss()) loop.create_task(send_media_instaloader()) loop.create_task(rss_parser.run()) # instaloader threads # instloader = InstagramLoader(config.INSTAGRAM_PARSER_LOGIN, config.INSTAGRAM_PARSER_PASSW) # instregister = InstagramLoaderRegistering(config.DATA_DIRECTORY_NO_RSS) # loop.create_task(instloader.run()) # loop.create_task(instregister.run()) loop.run_forever()
[ dict(text='Phone', request_contact=True), KeyboardButton(text='Location', request_location=True) ], ]) await bot.sendMessage(chat_id, 'Thank you!', reply_markup=markup) if command == 'ok' or 'Ok' or 'OK': await bot.sendMessage( chat_id, "Hi there. Now I will send you the pdf below ...") await bot.sendDocument(chat_id, document=open('Grading.pdf', 'rb')) elif command == 'thank you' or 'thanks' or 'thanks bro' or 'thank you bro': await bot.sendMessage(chat_id, "Welcome :)") # await bot.sendMessage(chat_id, "You said '{}'".format(command)) TOKEN = '' bot = telepot.aio.Bot(TOKEN) loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot, handel).run_forever()) # also we may use bot.message_loop(handle) print("Listening ...") # keep the program running loop.run_forever()
ShippingOption(id='fedex', title='FedEx', prices=[ LabeledPrice(label='Local', amount=345), LabeledPrice(label='International', amount=2345)]), ShippingOption(id='dhl', title='DHL', prices=[ LabeledPrice(label='Local', amount=342), LabeledPrice(label='International', amount=1234)])]) async def on_pre_checkout_query(msg): query_id, from_id, invoice_payload, currency, total_amount = telepot.glance(msg, flavor='pre_checkout_query', long=True) print('Pre-Checkout query:') print(query_id, from_id, invoice_payload, currency, total_amount) pprint(msg) print(PreCheckoutQuery(**msg)) await bot.answerPreCheckoutQuery(query_id, True) TOKEN = sys.argv[1] PAYMENT_PROVIDER_TOKEN = sys.argv[2] bot = telepot.aio.Bot(TOKEN) loop = asyncio.get_event_loop() loop.create_task( MessageLoop(bot, { 'chat': on_chat_message, 'shipping_query': on_shipping_query, 'pre_checkout_query': on_pre_checkout_query}).run_forever()) loop.run_forever()
with aiohttp.ClientSession(connector=connector) as session: async with session.get(url, params=params, headers=headers) as resp: return await resp.text() async def check_queue(): while 1: while not sender_queue.empty(): await sender(sender_queue.get()) await asyncio.sleep(0.1) load_plugins() bot = telepot.aio.Bot(config['token']) answerer = telepot.aio.helper.Answerer(bot) loop = asyncio.get_event_loop() loop.create_task( MessageLoop( bot, { 'chat': handle_messages, 'callback_query': on_callback_query, 'inline_query': on_inline_query, 'chosen_inline_result': on_chosen_inline_result, 'edited_chat': handle_messages }).run_forever()) loop.create_task(check_queue()) print('Bot Started ...') loop.run_forever()
""" async def updateModule(user_id, msg): replymsg = [] if user_id in TUser: pass else: Logger.logger.log("Warning::User ID {} is Trying to Access Modulefile") pass isChecked = False async def messagehandler(msg): flavor = telepot.flavor(msg) content_type, chat_type, chat_id = telepot.glance(msg, flavor=flavor) _msg = telepot.namedtuple.Message(**msg) #namedtuple if content_type == 'file': pass token = sys.argv[1] bot = telepot.aio.Bot(token) #Logger.logger.log() loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot, messagehandler).run_forever()) Logger.logger.log("Cambot Initialized") loop.run_forever()
elif vreveal >= vexpand: message = "Avete deciso di rivelare i nomi utenti!\n" for user in waffle.users: message += "- {user.icon} era {user}\n" message = "Il Waffle è stato sciolto.\n" \ "Se vi siete divertiti, create un gruppo normale!" await waffle.message(b, message) session.delete(waffle) session.commit() else: waffle.status = WaffleStatus.MATCHMAKING session.commit() await waffle.message( b, "Avete deciso di espandere il Waffle!\n" "Ricerca di altri giocatori in corso...\n" "Attendete, per piacere!") ml = MessageLoop(b, on_message) l.create_task(ml.run_forever()) l.create_task(matchmaking(900)) reloading = session.query(Waffle).filter( Waffle.status == WaffleStatus.CHATTING).all() for waffle in reloading: l.create_task(votes(21600, waffle.id)) l.create_task( waffle.message( b, "Oops! Il bot è stato riavviato e il timer della votazione è ricominciato.\n" "La votazione finirà tra 6 ore.")) l.run_forever()