async def post_details(self, bot, msg, par, header='', post=None): """ Sends the details of the event to the chat at update.message.chat_id If post == True, message will be posted by the event. If False, the event will return only the message. """ if not self.is_evt: await self.no_event(bot, par) return callback = dict(arg=self.init_kwd, chat_id=par['chat_id']) shotgun = config.res_kwd unshotgun = config.unres_kwd ready = config.rdy_kwd unready = config.unrdy_kwd keyboard = InlineKeyboardMarkup(inline_keyboard=[ [ InlineKeyboardButton( text='Shotgun', callback_data=str(dict(callback, **dict(cmd='/' + shotgun)))), InlineKeyboardButton(text='Ready-Up', callback_data=str( dict(callback, **dict(cmd='/' + ready)))), ], [ InlineKeyboardButton(text='Un-shotgun', callback_data=str( dict(callback, **dict(cmd='/' + unshotgun)))), InlineKeyboardButton( text='Not ready', callback_data=str(dict(callback, **dict(cmd='/' + unready)))), ] ]) txt = self.info_message(header) if not post: await bot.sendMessage(text=txt, parse_mode='Markdown', reply_markup=keyboard, chat_id=par['chat_id']) else: #strange telegram bug causes thread crash when #editing message to be the same (e.g same callback button #pressed twice. Message is first edited to be reverse of #true message, before editing to be the correct updated #message await bot.editMessageText(telepot.origin_identifier(msg), text=txt[::-1], parse_mode='Markdown') await bot.editMessageText(telepot.origin_identifier(msg), text=txt, parse_mode='Markdown', reply_markup=keyboard)
async def on_callback_query(self, msg): query_id, from_id, query_data = glance(msg, flavor='callback_query') try: data = self.deserialize(query_data) except ThatsNotMineException: return name = await get_user_name(msg['from']) text_as_list = msg['message']['text'].split("\n") for i in range(len(text_as_list)): if text_as_list[i][:2] == data: if name in text_as_list[i]: text_as_list[i] = await remove_name( text_as_list[i], name) else: text_as_list[i] = await add_name( text_as_list[i], name) new_text = "\n".join(text_as_list) with self.messages_table as table: entry = table.find_one(msg_id=msg['message']['message_id']) db_keyboard = dill.load(open(entry['keyboard_filename'], 'rb')) await self.bot.editMessageText( telepot.origin_identifier(msg), text=new_text, reply_markup=db_keyboard)
def on_callback_query(self, msg): ''' Handle ballot ''' query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') if telepot.origin_identifier(msg) != self._ballot_ident: self._revoke_ballot(telepot.origin_identifier(msg)) else: msg = self._polls[-1].vote(self._stu_id, query_data) self._ballot_view.editMessageText( text='{question}\n選擇:{choice}'.format( question=self._polls[-1].question, choice=query_data), reply_markup=None) self._ballot_view = None self._ballot_ident = None
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') message_id = telepot.origin_identifier(msg) print 'id:' + str(message_id) if query_data != 'cancel': try: points_avail = db.get_total(from_id)[0] if int(query_data)*10 < points_avail: points.redeem(query_data,from_id) msg_txt = 'Points redeemed = ' + str(int(query_data)*10) bot.editMessageText(message_id,msg_txt,reply_markup = None) points.total(from_id) else: msg_txt = 'Insufficient points ):' points.total(from_id) bot.editMessageText(message_id,msg_txt,reply_markup = None) except Exception as e: print e else: bot.editMessageText(message_id,'Cancelled',reply_markup = None)
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') msg_identifier = telepot.origin_identifier( msg ) #retrieves message identifier from callback query [chat id, msg id] user_tup = get_user(msg) #gets username and id state = ('leave', 'absent', 'present') if msg_identifier in bot_mem: # Check for poll existence poll = bot_mem[msg_identifier] # Gets referenced poll if query_data == 'present_pub': bot.sendMessage(from_id, poll.publish('stay')) bot.answerCallbackQuery(query_id, 'Published!') elif query_data == 'absent_pub': bot.sendMessage(from_id, poll.publish('absent')) bot.answerCallbackQuery(query_id, 'Published!') elif query_data in state: poll.edit_status(user_tup, query_data) result_tup = poll.get_result() bot.editMessageText(msg_identifier, result_tup[5], reply_markup=rollkey) #modify poll with answer bot.answerCallbackQuery(query_id, 'Answer Submitted') else: print('poll not found') bot.answerCallbackQuery(query_id, 'Poll Error, Try starting new Roll call')
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') if persistent_menu_mode: message_identifier = telepot.origin_identifier(msg) if query_data == 'camera1': keyboard = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text="Second camera", callback_data='camera2'), InlineKeyboardButton(text="Menu", callback_data='menu'), ]]) if persistent_menu_mode: BOT.editMessageText(message_identifier, "First Camera", reply_markup=keyboard) else: get_channel_frame(1) BOT.sendPhoto(from_id, photo=open('frame1.jpg', 'rb'), caption="First Camera 1") get_channel_frame(2) BOT.sendPhoto(from_id, photo=open('frame2.jpg', 'rb'), caption="First Camera 2") BOT.sendMessage(from_id, "Showing first camera...", reply_markup=keyboard) if query_data == 'camera2': keyboard = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text="First camera", callback_data='camera1'), InlineKeyboardButton(text="Menu", callback_data='menu'), ]]) if persistent_menu_mode: BOT.editMessageText(message_identifier, "Second Camera", reply_markup=keyboard) else: get_channel_frame(3) BOT.sendPhoto(from_id, photo=open('frame3.jpg', 'rb'), caption="Second Camera 1") get_channel_frame(4) BOT.sendPhoto(from_id, photo=open('frame4.jpg', 'rb'), caption="Second Camera 2") BOT.sendMessage(from_id, "Showing second camera...", reply_markup=keyboard) if query_data == 'menu': template = start_menu() if persistent_menu_mode: BOT.editMessageText(message_identifier, template[0], reply_markup=template[1]) else: BOT.sendMessage(from_id, template[0], reply_markup=template[1])
async def on_callback_query(self, msg): query_id, from_id, query_data = glance(msg, flavor='callback_query') try: data = self.deserialize(query_data) except ThatsNotMineException: return await self.bot.editMessageText( telepot.origin_identifier(msg), text="Selected option: {}".format(data), reply_markup=self.keyboard)
async def on_callback_query(self, msg): query_id, from_id, query_data = glance(msg, flavor='callback_query') try: data = self.deserialize(query_data) except ThatsNotMineException: return await self.bot.editMessageText(telepot.origin_identifier(msg), text="Mode changed to: {}".format(data), reply_markup=self.keyboard) if data == 'Picture': self.my_dice.mode = 'pic' self.my_coin.mode = 'pic' elif data == 'Text': self.my_dice.mode = 'txt' self.my_coin.mode = 'txt'
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') chat_id = telepot.origin_identifier(msg) #chat_id of group is obtained chat_id = chat_id[0] chat_id = str(chat_id) print(query_data + " requested from " + chat_id) if query_data == "summarise": db.__init__("ChatDB") startSummarise(chat_id) elif query_data == "clear": db.__init__("ChatDB") db.remove_Message(chat_id, messages) bot.sendMessage(chat_id, "Messages have been cleared.") elif query_data == "feedback": bot.sendMessage( chat_id, "Type \'/feedback [your feedback here]\' to send us some feedback!" )
async def edit_check_list(self, origin_msg, data): self.logger.debug("Origin message:\n" + str(origin_msg)) self.logger.debug( "Shopping list as list:\n" + str(self.parse_check_list(origin_msg['message']['text']))) self.logger.debug("Data: " + str(data)) try: data = int(data) except Exception as e: self.sender.sendMessage("Sorry, something went wrong.") raise e list_title, check_list = self.parse_check_list( origin_msg['message']['text']) if ListBeard.item_prefix in check_list[data]: check_list[data] = check_list[data].replace( ListBeard.item_prefix, ListBeard.item_done_prefix, ) elif ListBeard.item_done_prefix in check_list[data]: check_list[data] = check_list[data].replace( ListBeard.item_done_prefix, ListBeard.item_prefix, ) else: assert False, "Hmm, shouldn't get here..." keyboard = self.make_keyboard(check_list) text = self.format_check_list(list_title, check_list) await self.bot.editMessageText( origin_identifier(origin_msg), text=text, reply_markup=keyboard, ) query_id, from_id, query_data = glance(origin_msg, flavor='callback_query') await self.bot.answerCallbackQuery(query_id, check_list[data])
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 on_callback_query(msg): global msg_to_save global msg_dir query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') chat_id = msg["message"]["chat"]["id"] msg_id = telepot.origin_identifier(msg) if msg_to_save.get(chat_id,[]) and (msg_to_save.get(chat_id,[]).get("saved","") == False): # utente invia segnalazione corretta: calcolo della categoria e richiesta di conferma # oppure utente invia foto e conferma che segnalazione precedente va associata alla foto if (query_data == "save"): ts = time.strftime("%Y-%m-%d--%H-%M-%S", time.localtime(time.time())) + "__" + str(time.time()) msg_dir = "inbox/" + ts try: os.makedirs(msg_dir) except: pass try: X = msg_to_save[chat_id].get("text", "") # response = """Grazie!\nHo ricevuto la sua segnalazione: "%s".\n/menu_principale """ % (X[0]) ##CALCOLO CATEGORIA TESTO print(X) text_dict,category = None,None if (X): category, categories_prob = predict_text(X) text_dict = create_prob_dict(categories_prob) msg_to_save[chat_id]["text_category"] = text_dict # CALCOLO CATEGORIA FOTO photo_list = msg_to_save[chat_id].get("photo", []) photo_dict_array = [] if photo_list: # msg_to_save[chat_id]["photo_category"] = [] i = 0 for photo in photo_list: photo_id = photo["file_id"] # dimensione maggiore filename = msg_dir + "/" + photo_id + ".jpg" bot.download_file(photo_id, filename) photo_category, photo_prob = predict_image(filename) dict_prob = create_prob_dict(photo_prob) msg_to_save[chat_id]["photo"][i]["photo_category"] = dict_prob photo_dict_array.append(dict_prob) i += 1 print (category, photo_category) issue_category = predict_issue(text_dict,photo_dict_array) print(issue_category) msg_to_save[chat_id]["category"] = issue_category keyboard_btns = [] L = [] L.append(InlineKeyboardButton(text="Si", callback_data="si")) L.append(InlineKeyboardButton(text="No", callback_data="no")) keyboard_btns.append(L) keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) response = """Grazie!\nHo ricevuto la sua segnalazione. Calcolato categoria %s: è corretta?""" % (issue_category) bot.editMessageText(msg_id, response, reply_markup=keyboard) except: print (traceback.format_exc()) # utente sceglie di aggiungere altre informazioni ( non necessario, può semplicemente scrivere altro testo) elif (query_data == "add"): keyboard_btns = [] keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) text = """Può inserire un altro messaggio, una foto o la posizione da associare a questa segnalazione""" bot.editMessageText(msg_id, text, reply_markup=keyboard) # utente annulla segnalazione elif (query_data == "delete"): keyboard_btns = [] keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) text = """Segnalazione eliminata. Può scriverne una nuova""" msg_to_save[chat_id]["saved"] = True bot.editMessageText(msg_id, text, reply_markup=keyboard) # KEYBOARD DI GESTIONE SCELTA CATEGORIA (query_data = ["si","no","altri"] # utente conferma che categoria calcolata è corretta: posso salvare la segnalazione elif (query_data == "si"): keyboard_btns = [] keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) text = """Grazie! La sua segnalazione associata alla categoria %s è stata registrata correttamente. \nPuò inserire una nuova segnalazione""" % \ msg_to_save[chat_id].get("category","") bot.editMessageText(msg_id, text, reply_markup=keyboard) ##SALVATAGGIO msg_to_save[chat_id]["saved"] = True pprint.pprint(msg_to_save[chat_id], open(msg_dir + "/" + 'msg.dict', 'w')) segnalazione = msg_to_segnalazione(msg_to_save[chat_id], msg_dir) if segnalazione: segnalazione.printIssue() segnalazione.save() with open(msg_dir + "/" + 'issue.pickle', 'wb') as output: pickle.dump(segnalazione, output, pickle.HIGHEST_PROTOCOL) # categoria calcolata per utente è sbagliata: chiedo direttamente quale sia quella corretta elif (query_data == "no"): keyboard_btns = [] for row in REPLY_BUTTONS_TEXT: L = [] for col in row: L.append(InlineKeyboardButton(text=col[0], callback_data=col[1])) keyboard_btns.append(L) keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) bot.editMessageText(msg_id, 'Scegli quale categoria è più corretta', reply_markup=keyboard) # tutte gli altri tipi di callback nascono quando utente sceglie categoria corretta. Poi posso salvare la segnalazione else: keyboard_btns = [] keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) text = """Grazie! La sua segnalazione associata alla categoria %s è stata registrata correttamente. \nPuò inserire una nuova segnalazione""" % query_data bot.editMessageText(msg_id, text, reply_markup=keyboard) if query_data == "altro": msg_to_save[chat_id]["category"] = None else: msg_to_save[chat_id]["category"] = query_data # salvataggio msg_to_save[chat_id]["saved"] = True pprint.pprint(msg_to_save[chat_id], open(msg_dir + "/" + 'msg.dict', 'w')) segnalazione = msg_to_segnalazione(msg_to_save[chat_id], msg_dir) if segnalazione: segnalazione.printIssue() segnalazione.save() with open(msg_dir + "/" + 'issue.pickle', 'wb') as output: pickle.dump(segnalazione, output, pickle.HIGHEST_PROTOCOL) else: #quando utente preme una vecchia keyboard e il messaggio è già stato inviato keyboard_btns = [] keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_btns) text = "Grazie!" bot.editMessageText(msg_id, text, reply_markup=keyboard) bot.answerCallbackQuery(query_id, text="")
async def on_callback_query(self, msg): query_id, from_id, query_data = glance(msg, flavor='callback_query') match = None try: # Get current text in the message data = self.deserialize(query_data) r_id = data['rid'] name = data['name'] if name == 'goal_kb': with self.goal_table as table: match = table.find_one(rid=r_id) if not match: # Ignore where entry is already deleted print("Entry already deleted") return if match['uid'] != from_id: # Ignore where another user tries to delete an entry # Thogh this shouldn't be possible... print("User tried to delete an entry that was not their's") return # Delete the item table.delete(rid=r_id) # Update the list of goals items = await self._get_user_goals(from_id) if items: keyboard = await self._make_keyboard(items, 'goal_kb') await self.bot.editMessageText( telepot.origin_identifier(msg), text='Your current goals. Click on a goal to remove it', reply_markup=keyboard) else: await self.bot.editMessageText( telepot.origin_identifier(msg), text='You have no goals at the moment.') elif name == 'rmd_kb': with self.reminders_table as table: match = table.find_one(rid=r_id) if not match: # Ignore where entry is already deleted print("Entry already deleted") return if match['uid'] != from_id: # Ignore where another user tries to delete an entry # Thogh this shouldn't be possible... print("User tried to delete an entry that was not their's") return # Delete the item table.delete(rid=r_id) # Update the list of goals items = await self._get_user_reminders(from_id) if items: keyboard = await self._make_keyboard(items, 'rmd_kb') await self.bot.editMessageText( telepot.origin_identifier(msg), text='Your current reminders. Click on a reminder to remove it.', reply_markup=keyboard) else: await self.bot.editMessageText( telepot.origin_identifier(msg), text='You have no reminders at the moment.') except ThatsNotMineException: pass
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') msg_identifier = telepot.origin_identifier(msg) if msg['message']['chat']['id'] in settings.ALOWED_CHATS: print('Callback Query:', query_id, from_id, query_data) print('Chat_id', msg['message']['chat']['id']) logging.warning('Telegram raw data %s' % msg['message']['chat']['id']) user = get_or_create_user(msg) if query_data == 'yes' and user.voted is False: user.voted = True user.save() iteration = len(TelegramUser.objects.filter(voted=True)) keyboard1 = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text=f'Доставлена ({iteration})', callback_data='yes') ]]) bot.editMessageReplyMarkup(msg_identifier, reply_markup=keyboard1) if iteration >= 2: TelegramUser.objects.filter(voted=True).update(voted=False) organisation = Organisation.objects.get(buyer=True) organisation.buyer = False organisation.save() if len(Organisation.objects.all()) <= organisation.order: organisation.order = 0 next_order = organisation.order + 1 next_organisation = Organisation.objects.get(order=next_order) next_organisation.buyer = True next_organisation.save() bot.editMessageText( msg_identifier, f'Следующий заказывает {str(next_organisation.name)}') bot.answerCallbackQuery(query_id, text='Голос получен') elif query_data == 'yes' and user.voted is True: bot.answerCallbackQuery(query_id, text='Вы уже подтверждали') elif query_data == 'open': door_usage = DoorUsage() door_usage.id_user = TelegramUser.objects.get( id_telegram=user.id_telegram) door_usage.request_door_time = datetime.now() door_usage.save() # last_opening = Organisation.objects.last().opened_door_time if user.can_open_door: #and last_opening + datetime.timedelta(seconds=settings.DOOR_SLEEP_TIME) > datetime.now(): data = { 'command': 'open', } headers = { 'Content-type': 'application/json', 'Authorization': settings.DOOR_AUTH, } r = requests.post(settings.DOOR_URL, headers=headers, data=json.dumps(data)) print(r.json()) if r.status_code == 200: # last_opening = datetime.now() # last_opening.save() bot.answerCallbackQuery(query_id, text='Дверь открыта')
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') msg_update = telepot.origin_identifier(msg) username = get_username(msg) if 'inline_message_id' in msg: inline_message_id = msg['inline_message_id'] else: inline_message_id = user_state[from_id][3] if inline_message_id == None: # When admin wants to add order and no one has added yet. origin_user, origin_msg_id = msg_update retrieved_order = order_pad[origin_user][ origin_msg_id] #Retrieves the target orderlist else: retrieved_order = order_master_list[ inline_message_id] #Retrieves the target orderlist title = retrieved_order.get_title() if query_data == 'add_order': if retrieved_order.get_lock_status(): bot.sendMessage(from_id, 'The orderlist is locked') bot.answerCallbackQuery(query_id, text='Order locked!') elif username in retrieved_order.get_orders(): bot.sendMessage( from_id, 'Order exist! Delete order and then place a new order') bot.answerCallbackQuery(query_id, text='Order Exist') else: order_req = bot.sendMessage(from_id, 'Adding order, what is your order?') order_user_id, order_text_id = telepot.message_identifier( order_req) user_state[from_id] = [ True, order_text_id + 1, 'add_order', inline_message_id, retrieved_order.get_admin_id() ] #set bot to take next input from user as order bot.answerCallbackQuery(query_id, text='Adding order') if query_data == 'del_order': if retrieved_order.get_lock_status(): bot.sendMessage(from_id, 'The orderlist is locked') bot.answerCallbackQuery(query_id, text='Order locked!') elif username in retrieved_order.get_orders(): previous_order = retrieved_order.get_user_order(username) retrieved_order.del_order(username) bot.sendMessage( from_id, ('Your previous order has been deleted:\n' + previous_order)) bot.answerCallbackQuery(query_id, text='Order deleted') else: bot.sendMessage(from_id, 'No order has been placed') bot.answerCallbackQuery(query_id, text='Please place order') if query_data == 'join_order': bot.sendMessage(from_id, ('Joining order: ' + title), reply_markup=retrieved_order.get_keyboard()) user_state[from_id] = [False, None, None, inline_message_id] bot.answerCallbackQuery(query_id, text='PM sent, check OrderJioBot chat') if query_data == 'update': try: bot.editMessageText(msg_update, retrieved_order.publish_order(), reply_markup=retrieved_order.get_keyboard()) except: pass bot.answerCallbackQuery(query_id, text='Orderlist updated!') if query_data == 'grp_update': try: bot.editMessageText(msg_update, retrieved_order.publish_order(), reply_markup=grp_keyboard) except: pass bot.answerCallbackQuery(query_id, text='Orderlist updated!') if query_data == 'admin_update': admin_keyboard = InlineKeyboardMarkup( inline_keyboard=admin_shared_buttons + [[InlineKeyboardButton(text='Publish', switch_inline_query=title)]] ) try: bot.editMessageText(msg_update, retrieved_order.publish_order(), reply_markup=admin_keyboard) except: pass bot.answerCallbackQuery(query_id, text='Orderlist updated!') if query_data == 'lock_order': retrieved_order.lock = True bot.answerCallbackQuery(query_id, text='Order has been locked') if query_data == 'unlock_order': retrieved_order.lock = False bot.answerCallbackQuery(query_id, text='Order has been unlocked')