async def handle(msg): print("===================") DBSession = sessionmaker(bind=engine) db_session = DBSession() flance = telepot.flance(msg) print(flance) pprint(msg) if flance[0] == "chat": if flance[1][1] == "channel": await channel_handler(msg) elif flance[1][1] == "group": group_handler(msg) elif flance[1][1] == "private": await private_handler(msg, db_session) elif flance[0] == "callback_query": tg_user_id = msg['from']['id'] callback_query = msg['data'] msg_id = msg['message']['message_id'] db_tg_user = utils.get_tg_user(db_session, tg_user_id) if callback_query == "cancel_command": DIALOG_STATE = "" #ДОЛЖНО БЫТЬ В БАЗЕ sent = await bot.deleteMessage((tg_user_id, msg_id)) else: print("Not a 'chat'") try: db_session.close() except: print("Database session was not closed") print("///////////////////")
async def handle(self, msg): flavor, details = telepot.flance(msg) # TODO: log? if flavor == "chat" and details[0] == "text": logging.info(f"Received message: {msg['text']}") content_type, chat_type, chat_id = details cmd, *cmd_args = msg["text"].split(" ") if not cmd.startswith("/"): logging.info("No predicate. Ignoring.") return func = self.cmds[cmd] if not func: logging.info("Not a valid function.") return tuuba = self._loop.run_in_executor(None, func, chat_id, *cmd_args) msg = await asyncio.wait_for(tuuba, None) if not msg: msg = "202 no content" await self.send_message(chat_id, msg) # await self.cmds[cmd]( # self, type=chat_type, id=chat_id, cmd=cmd, args=cmd_args) elif flavor == "inline_query": query_id, sender_id, query = details # Handle inline query pass elif flavor == "chosen_inline_result": result_id, sender_id, query = details # Handle chosen inline result pass elif flavor == "callback_query": query_id, sender_id, data = details # Handle callback query pass
async def handler(msg): # I may have to refactor this function, this is way too ugly. I just want a case-switch. pprint(telepot.flance(msg,long=True)) # Logging info... try: # Handle the commands if msg['text'].startswith('/contributions'): await getContribution(bot,msg) elif msg['text'].startswith('/start'): await bot.setMessage(msg['chat']['id'],'This is Feza Bot NG.') elif msg['text'].startswith('/help'): await botHelp(bot,msg) elif msg['text'].startswith('/random'): await trueInteger(bot,msg) elif msg['text'].startswith('/lookup'): await getdns(bot,msg) elif msg['text'].startswith('/hacker'): await hackerize(bot,msg) elif msg['text'].startswith('/sad'): await sad(bot,msg) elif msg['text'].startswith('/wttr'): await getWttr(bot,msg) elif msg['text'].startswith('/urldecode'): await urldecode(bot,msg) elif msg['text'].startswith('/ocr'): # Disable OCR due to poor effciency. #await ocr(bot,msg) pass elif msg['text'].startswith('/hash'): await ihash(bot,msg) elif msg['text'].startswith('/translate'): await translate(bot,msg) elif msg['text'].startswith('/support'): await zici(bot,msg) elif msg['text'].startswith('/kuaidi'): await kuaidi(bot,msg) except KeyError as e: # It may throw something at me. And I hate it. pprint(e)
async def handler(msg): pprint(telepot.flance(msg, long=True)) # logging info. try: if random.randint(0, 10) == 1: if 'sticker' in msg: await bot.sendSticker(msg['chat']['id'], msg['sticker']['file_id']) if msg['text'].startswith('/bmi'): await bmi(bot, msg) elif msg['text'].startswith('/whois'): await whois(bot, msg) elif msg['text'].startswith('/kuaidi'): await kuaidi(bot, msg) elif msg['text'].startswith('/pixiv'): await pixiv(bot, msg) elif msg['text'].startswith('/cur'): await cur(bot, msg) elif msg['text'].startswith('/wikipedia_summary'): await wikipedia_summary(bot, msg) elif msg['text'].startswith('/start'): await bot.sendSticker(msg['chat']['id'], 'CAADBQADoAADrGw9CXcrhedlPDgCAg') elif msg['text'].startswith('/decided'): await decided(bot, msg) else: pass if re.search(r'[qpbd]+[wau]+[qpbd]', msg['text']) != None: await miaow(bot, msg) except KeyError as e: pprint(e)
def on_chat_message(msg): flavors = telepot.flance(msg)[0] content_type, chat_type, chat_id = telepot.flance(msg)[1] if checkchat_id(chat_id): response = '' # pprint.pprint(msg) if content_type == 'text': command = msg['text'] if command.startswith('/shell'): sc = command[len('/shell'):] if sc != '': out = shell.run(sc) else: out = shell.run('whoami') bot.sendChatAction(chat_id, 'typing') response = out.decode('gbk') elif command == '/screenshot': capshot.get_shot('screenshot.jpg') bot.sendChatAction(chat_id, 'upload_photo') bot.sendDocument(chat_id, open('screenshot.jpg', 'rb')) os.remove('screenshot.jpg') elif command == '/camerashot': capshot.get_cams('camerashot.jpg') bot.sendChatAction(chat_id, 'upload_photo') bot.sendDocument(chat_id, open('camerashot.jpg', 'rb')) os.remove('camerashot.jpg') elif content_type == 'document': file_id = msg['document']['file_id'] file_name = msg['document']['file_name'] bot.download_file(file_id, file_name) bot.sendChatAction(chat_id, 'upload_document') response = 'File saved as ' + file_name if response != '': if len(response) - 1 < 4096: print(response) send_message(chat_id, response) else: with open("output.txt", "w") as f: f.write(response) bot.sendDocument(chat_id, open('output.txt', 'rb')) os.remove('output.txt') send_message(chat_id, '太长了!!!')
async def on_chat(msg): flance = telepot.flance(msg) if flance[0] != "chat": return if flance[1][0] == "new_chat_member": name = msg["new_chat_member"]["first_name"] chat = msg["chat"]["id"] await bot.sendMessage( chat, """Hello recruit! \n I see in here that your name is """ + name + """, is it correct?\n Well, let's get started. I need you to send me your recruitment code, it's the 6 letter code (ABC DEF) at top of your [🏅Me] tab\n You can just paste it in here or forward you [🏅Me] tab to this chat, either is fine.\n After that, I want you to take a look at our recruit guide: https://docs.google.com/document/d/165zIp74mQsn540ClqfNWtpFnLKqCqNbgtxMwj9OwjO8/edit?usp=drivesdk\n Everything you need to know should be there, but if any doubts shall fill this little helm of yours, just let us know.\n Now fly high, recruit!""") elif flance[1][0] == "text": chat = msg["chat"]["id"] if msg["text"].find("/call") == 0: trusted = [ int(each) for each in os.environ["trusted_list"].split("#") ] print(msg["from"], msg["from"]["id"] in trusted) if msg["from"]["id"] in trusted: global context orders = msg["text"][6:] keyboard = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text="Sir, yes sir!", callback_data="click") ]]) inline_message = await bot.sendMessage( chat, "C A L L T O A R M S !\nOrders:\n" + orders, reply_markup=keyboard) cont = { "inline_message": inline_message, "count": 0, "clicked": [], "orders": orders } try: context.update({chat: cont}) except: #is not defined yet context = {chat: cont}
def on_chat_message(self, msg): flavor, info = telepot.flance(msg) if flavor == 'chat' and info[0] != 'text': self.sender.sendMessage(self.t('only_text')) return text = msg.get('text', '').strip() if not text: return if text[0] == '/': command = text.split() command[0] = command[0].lower() else: command = [None] if command[0] == '/help': self._send_help() elif not self.has_user: no_code_msg = self.t('no_code') if command[0] == '/start': if len(command) == 1: self.sender.sendMessage(no_code_msg.format( config.BASE_URL)) return hashcode = command[1] else: hashcode = text.strip() if len(hashcode) != 64: self.sender.sendMessage(no_code_msg.format(config.BASE_URL)) return user = self._find_user_by_code(hashcode) if not user: self.sender.sendMessage( self.t('wrong_code') + '\n' + no_code_msg.format(config.BASE_URL)) return Telegram.create(channel=self.id, user=user) self.lang = load_language(user) self.sender.sendMessage(self.t('welcome').format(user.name)) self._set_reminder('') self._print_task() else: if command[0] == '/task': self._print_task() elif ch.RE_CHANGESET.match(text): self._register_changeset(text) elif command[0] == '/list': self._list_changesets() elif command[0] == '/done': self._last_changeset() elif command[0] == '/now': self._set_reminder('') elif command[0] == '/remind': if len(command) == 1 or not RE_TIME.match(command[1]): self.sender.sendMessage(self.t('which_utc')) else: self._set_reminder(command[1]) elif RE_TIME.match(text): self._set_reminder(text) elif command[0] == '/when': self._print_reminder() elif command[0] == '/stop': self._set_reminder(None) elif command[0] == '/start': self.sender.sendMessage( self.t('already_logged').format(self._get_tg().user.name)) elif command[0] == '/whoami': self.sender.sendMessage( self.t('you_are').format(self._get_tg().user.name)) elif command[0] == '/score': self._print_score() elif command[0] == '/lang': self._set_lang(None if len(command) < 2 else command[1]) else: self.sender.sendMessage(self.t('unknown_cmd'))
def post(self, request, **kwargs): # Telegram token is defined in URLs token = kwargs.get('token', None) bot = telepot.Bot(token) # request.body is "bytes" s = request.body.decode("utf-8") # string msg = json.loads(s) update_id = None if 'update_id' in msg: for key in msg: if key == 'update_id': update_id = msg['update_id'] else: msg = msg[key] # Example: # {message: {chat: {}, date: 1515851945, from: {}, message_id: # 174, text: H}, update_id: 185696256} # try: # message = j['message'] # except Exception: # print(j) # client.captureException() try: flavor = telepot.flavor(msg) except Exception: client.captureException() return HttpResponse("") # chat_id = message['chat']['id'] if flavor == 'callback_query': query_id, from_id, query_data = telepot.flance(msg)[1] # query_id == 6479684549687354674 (really big) # query_data == "publish" / "skip" / "spam" (chat_id, message_id) = telepot.origin_identifier(msg) user = None try: user = User.objects.get(telegram_chat_id=chat_id) except Exception: pass bot.answerCallbackQuery(query_id, text=str(user) + ': ' + str(query_id)) bot.deleteMessage(telepot.origin_identifier(msg)) # telepot.origin_identifier(msg) # bot.sendMessage( # chat_id, # "echo2: "+text, # ) # This part is invoked when a new message is received or when a # user starts a chat with my bot. elif flavor == 'chat': content_type, chat_type, chat_id = telepot.flance(msg)[1] text = msg['text'] # Someone's pressed Telegram's "/start" button: if text.startswith('/start '): words = text.split() token = words[-1] user_id = cache.get(self.key.format(token)) if user_id: try: user = User.objects.get(pk=user_id) user.telegram_chat_id = chat_id user.save() bot.sendMessage( chat_id, "Привет, " + str(user), ) except User.DoesNotExist: client.captureException() self.key.format(token) # Any other message here. Answer the prayer: else: bot.sendMessage( chat_id, "echo2: " + text, # parse_mode=None, # disable_web_page_preview=None, # disable_notification=None, # reply_to_message_id=None, # reply_markup=None ) else: log.error('unknown message: ' + str(msg)) return HttpResponse("")
def handle(msg): global data pprint(msg) typeOfMsg = telepot.flance(msg)[0] if typeOfMsg == 'chat': query = '' chat_id = msg['chat']['id'] flag = msg['text'].split('@')[1] command = msg['text'].split('@')[0] command = command.split(' ') message_id = msg['message_id'] username = '******' + msg['from']['username'] # print(command[0]) # print(flag) elif typeOfMsg == 'inline_query': command = [None] flag = 'pickLunch_bot' query = msg['query'] query_id = msg['id'] else: pass if flag != 'pickLunch_bot': return 0 else: pass if command[0] == '/eat': length = len(command) if length == 1: eat(data, msg) elif int(command[1]) > 10: bot.sendPhoto( chat_id, 'https://i.ytimg.com/vi/AWgDNOxroB8/maxresdefault.jpg', reply_to_message_id=message_id) else: eat(data, msg, int(command[1])) elif command[0] == '/crawl': try: bot.sendMessage(chat_id, '關鍵字: {}...爬蟲中...'.format(command[1])) data[chat_id] = crawl(command[1]) if len(data[chat_id]) == 0: bot.sendPhoto( chat_id, 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGkV4N8ErJIFIrAac1IGcvagr5Du89GsZZwJg25J3js4THChjyjw', reply_to_message_id=message_id) bot.sendMessage(chat_id, '你確定{}是可以吃的嗎???'.format(command[1]), reply_to_message_id=message_id) else: bot.sendMessage(chat_id, '資料更新完成!!') except BaseException: bot.sendMessage(chat_id, '關鍵字: 北科大...爬蟲中...') data = crawl('北科大') bot.sendMessage(chat_id, '資料更新完成!!') elif command[0] == '/help': bot.sendMessage(chat_id, HELP) elif query == 'surprise': article = [{ 'type': 'article', 'id': '1', 'title': '彩蛋', 'input_message_content': { 'message_text': '你找到彩蛋了!' } }] print(article) bot.answerInlineQuery(query_id, article)