async def namehandler(self, msg): packname = msg['text'] + '_by_batchstickerbot' namevalid = validate_stickers.name(packname) try: packexists = await bot.getStickerSet(packname) except telepot.exception.TelegramError: packexists = False if namevalid and not packexists: self.packname = packname await self.sender.sendMessage(self.asktitle, reply_markup=ForceReply()) else: await self.sender.sendMessage(self.retryname, reply_markup=ForceReply())
def phone_number_confirmed(self, chat_id, c): if c.pending_order_gift_id \ and c.pending_order_gift_id != '': gift = None for g in self.dri.gifts: if c.pending_order_gift_id == g.id: gift = g break if gift is None: return bot.sendMessage(chat_id, 'لطفا آدرس را وارد نمایید.', reply_markup=ForceReply()) else: markup = ReplyKeyboardMarkup(keyboard=[ [KeyboardButton(text=new_gifts_fa)], [KeyboardButton(text=categories_fa)], [KeyboardButton(text=price_oriented_fa)], [KeyboardButton(text=about_us_fa)], ], resize_keyboard=True, one_time_keyboard=True) bot.sendMessage(chat_id, please_choose_fa, reply_markup=markup)
def messageSender(chatId, type, msg, *KBList): print(chatId, type, msg, *KBList) #todo: if have error #todo: if kbList is empty #todo: change false with return bot.sendMessage() if KBList: for items in KBList: keyboardList = items if type == 'text': bot.sendMessage(chatId, msg) if type == 'keyboard': keyboard = ReplyKeyboardMarkup(keyboard=keyboardList) bot.sendMessage(chatId, msg, reply_markup=keyboard) if type == 'hide': keyboard = ReplyKeyboardRemove() bot.sendMessage(chatId, msg, reply_markup=keyboard) if type == 'reply': markup = ForceReply() bot.sendMessage(chatId, msg, reply_markup=markup) if type == 'button': keyboard = InlineKeyboardMarkup(inline_keyboard=keyboardList) bot.sendMessage(chatId, msg, reply_markup=keyboard) if type == 'forward': for k in KBList: bot.forwardMessage(chatId, k, msg)
def query_user_new(chat_id, from_info, query): user_id, first_name = from_info['id'], from_info['first_name'] bot.sendMessage(chat_id, '[{}](tg://user?id={}), _{}_ is the event?'.format( first_name, user_id, query), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=ForceReply(selective=True))
async def on_chat_message(msg): 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'][-1:].lower() if command == 'c': markup = ReplyKeyboardMarkup(keyboard=[ ['Plain text', KeyboardButton(text='Text only')], [dict(text='Phone', request_contact=True), KeyboardButton(text='Location', request_location=True)], ]) await bot.sendMessage(chat_id, 'Custom keyboard with various buttons', reply_markup=markup) elif command == 'i': markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='Telegram URL', url='https://core.telegram.org/')], [InlineKeyboardButton(text='Callback - show notification', callback_data='notification')], [dict(text='Callback - show alert', callback_data='alert')], [InlineKeyboardButton(text='Callback - edit message', callback_data='edit')], [dict(text='Switch to using bot inline', switch_inline_query='initial query')], ]) global message_with_inline_keyboard message_with_inline_keyboard = await bot.sendMessage(chat_id, 'Inline keyboard with various buttons', reply_markup=markup) elif command == 'h': markup = ReplyKeyboardHide() await bot.sendMessage(chat_id, 'Hide custom keyboard', reply_markup=markup) elif command == 'f': markup = ForceReply() await bot.sendMessage(chat_id, 'Force reply', reply_markup=markup)
def check_for_address(self, chat_id, address): c = Customer.query.filter_by(tg_id=str(chat_id)).first() if c and c.customer_phone and c.customer_phone != '' and \ c.pending_order_gift_id and c.pending_order_gift_id != '': gift = None for g in self.dri.gifts: if c.pending_order_gift_id == g.id: gift = g break if gift is None: return c.destination_address = address db.session.commit() bot.sendMessage( chat_id, 'لطفا تناژ مورد نظر را به صورت یک عدد وارد نمایید.', reply_markup=ForceReply()) else: markup = ReplyKeyboardMarkup(keyboard=[ [KeyboardButton(text=new_gifts_fa)], [KeyboardButton(text=categories_fa)], [KeyboardButton(text=price_oriented_fa)], [KeyboardButton(text=about_us_fa)], ], resize_keyboard=True, one_time_keyboard=True) bot.sendMessage(chat_id, please_choose_fa, reply_markup=markup)
def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) print('Chat:', content_type, chat_type, chat_id) command = msg['text'].lower() if command == '/start': markup2 = ForceReply() # keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text=''),next key]],resize_keyboard=True) markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='How does it work', url='https://telegra.ph/Lists-of-Languages-available-in-the-bot-08-12')]]) responce = bot.getChat(chat_id) first_name = responce['first_name'] bot.sendChatAction(chat_id, 'typing') bot.sendMessage( chat_id, f'Hello <b>{first_name} </b>', parse_mode='html', reply_markup=markup2) bot.sendChatAction(chat_id, 'typing') bot.sendMessage(chat_id, 'Welcome to <b>babylon<b> translator chat bot this bot will help you to translate different languges and helps you to explore more and to communicate better.', parse_mode='html', reply_markup=markup) elif msg['text'] != '/start': message = msg['text'].lower() value = message.split(' ') if not '|' in value: markup = ReplyKeyboardRemove() translator = Translator() translation = translator.translate(f'{message}') translation_src_name = LANGUAGES[translation.src] bot.sendChatAction(chat_id, 'typing') bot.sendMessage( chat_id, f'Language has been detected <b>{translation_src_name}</b>', parse_mode='html', reply_markup=markup) bot.sendChatAction(chat_id, 'typing') time.sleep(0.5) bot.sendMessage(chat_id, f'{translation.text}', parse_mode='html') bot.sendChatAction(chat_id, 'UPLOAD_AUDIO') tts = gTTS(message, lang='en') tts.save('mk.mp3') with open('mk.mp3', 'rb') as speech: bot.sendChatAction(chat_id, 'UPLOAD_AUDIO') bot.sendVoice(chat_id, voice=speech, caption=None) speech.close() else: try: markup = ReplyKeyboardRemove() message = msg['text'].lower() value = message.split('|') user_text = value[0] user_dest = value[-1].strip() translator = Translator() translations = translator.translate( f'{user_text}', dest=f'{user_dest}') user_dest_name = LANGUAGES[user_dest] user_src_name = LANGUAGES[translations.src] bot.sendChatAction(chat_id, 'typing') bot.sendMessage( chat_id, f'From <b>{user_src_name}</b> to <b>{user_dest_name}</b>', parse_mode='html') bot.sendMessage( chat_id, f'<b>{translations.text}</b>', parse_mode='html') except ValueError: bot.sendMessage( chat_id, f'invalid destination! what does {user_dest} means see How does it works section!')
async def on_chat_message(self, msg): content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance( msg, long=True) # Make sure the user is private messaging us. if chat_type == 'private': # All the commands will be text, lets just make sure anyway. if content_type == 'text': command = msg['text'].lower() if command.startswith('/create'): await self.sender.sendChatAction('typing') await self.startstickers(msg) elif command.startswith('/done'): try: if self.packmade: await self.sender.sendMessage( 'All done! The sticker pack has been made and the stickers have been added, you can now manage it in the official stickers bot or access it right now with https://t.me/addstickers/' + self.packname) self.close() except AttributeError: return elif command.startswith('/edit'): #print(await bot.getStickerSet('rakutest3_by_batchstickerbot')) await self.sender.sendMessage(self.askedit, reply_markup=ForceReply()) # Check if the user is replying to one of the bots messages and whicih one it is. else: try: reply_msg = msg['reply_to_message'] reply_text = reply_msg['text'] #print(msg) if reply_text in (self.askname, self.retryname): await self.namehandler(msg) elif reply_text in (self.asktitle, self.retrytitle): await self.titlehandler(msg) elif reply_text == self.donemsg: self.stickeremoji = msg['text'] elif reply_text == self.askedit: await self.checkownership(msg) except KeyError: await self.sender.sendMessage(self.askreply) return # Stickers are added as documents. elif content_type == 'document': await self.uploader(msg) # We don't want them sent as photos elif content_type == 'photo': try: if (self.packname and self.packtitle) or self.editing: await self.sender.sendMessage( 'Please send the image as a file(uncompressed).', reply_to_message_id=msg_id) except AttributeError: pass return
def on_callback_query(msg): query_id, from_id, data = telepot.glance(msg, flavor='callback_query') # print('Callback query:', query_id, from_id, data) if data == 'tasisat': # print('Tasisat callback') if from_id in live_users: bot.sendMessage(from_id, 'یدونه یدونه!') return None live_users.append(from_id) bot.sendMessage(from_id, 'لطفا آیتم مورد نظر را بفرمایید', reply_markup=ForceReply()) elif data == 'lost': # print('lost callback') if from_id in live_users: bot.sendMessage(from_id, 'یدونه یدونه!') return None live_users.append(from_id) bot.sendMessage(from_id, 'لطفا آیتم مورد نظر را بفرمایید', reply_markup=ForceReply())
def send_message(self, data, message, reply_type = ''): chat_id = self.get_chat_id(data) user_id = self.get_user_id(data) user_firstname = self.get_user_firstname(data) mention = "<a href='tg://user?id={}'>{}</a>".format(user_id, user_firstname) self.bot.sendChatAction(chat_id, 'typing') if reply_type == 'ForceReply': markup = ForceReply(selective=True) response = self.bot.sendMessage(chat_id, message + ', ' + mention, parse_mode='HTML', reply_markup=markup) time.sleep(0.5) return response response = self.bot.sendMessage(chat_id, message) time.sleep(0.5) return response
async def on_chat_message(msg): 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'][-1:].lower() if command == 'c': markup = ReplyKeyboardMarkup(keyboard=[ [KeyboardButton(text='Location', request_location=True)], ]) await bot.sendMessage(chat_id, '키보드창의 Location 버튼을 눌러 현재위치를 확인하세요.', reply_markup=markup) elif command == 'i': markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='Telegram URL')], [ InlineKeyboardButton(text='Callback - show notification', callback_data='notification') ], [dict(text='Callback - show alert', callback_data='alert')], [ InlineKeyboardButton(text='Callback - edit message', callback_data='edit') ], [ dict(text='Switch to using bot inline', switch_inline_query='initial query') ], ]) global message_with_inline_keyboard message_with_inline_keyboard = await bot.sendMessage( chat_id, 'Inline keyboard with various buttons', reply_markup=markup) elif command == 'f': markup = ForceReply() await bot.sendMessage(chat_id, 'Force reply', reply_markup=markup)
def query_user_edit(chat_id, from_info, i, query): user_id, first_name = from_info['id'], from_info['first_name'] if query == 'description': content = planner.get_desc(chat_id, i) elif query == 'location': content = planner.get_loc(chat_id, i) elif query == 'date': content = planner.get_date(chat_id, i) elif query == 'time': content = planner.get_time(chat_id, i) else: content = "" bot.sendMessage( chat_id, "[{}](tg://user?id={}) *is editing the {} {}:*\n\n{}".format( first_name, user_id, query, emojis[query], content), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=ForceReply(selective=True))
def on_callback_query(self, msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') data = str(query_data).split(',') if data[0] == 'menu': if data[1] == 'Nome': markup = ForceReply() _forcedreply = bot.sendMessage(self.chat_id, 'Spara un nome!', reply_markup=markup) self._forcedreply_editor = telepot.helper.Editor( self.bot, _forcedreply) elif data[1] == 'Classe': self._send_classes() elif data[1] == 'Livello': self._send_levels() elif data[1] == 'Classe e Livello': self.level_expected = True self._send_classes() elif data[0] == 'class': self.class_to_find = data[1] if self.level_expected: self._send_levels() else: self._send_spells( self.spellbook.ottieniIncantesimiPerClasse( self.class_to_find), 2) elif data[0] == 'level': self.level_to_find = data[1].replace('Lv. ', '') if self.level_expected: self._send_spells( self.spellbook.ottieniIncantesimiPerClasseDiLivello( self.class_to_find, self.level_to_find), 0) else: self._send_spells( self.spellbook.ottieniIncantesimiDiLivello( self.level_to_find), 1) elif data[0] == 'spell': self._send_spell_message(data[1])
async def startstickers(self, msg): await self.sender.sendMessage(self.askname, reply_markup=ForceReply()) self.packmade = False return
def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) ## print(msg) ## for i in chat_list: ## if i['user1']==str(chat_id): ## if content_type=="text": ## if msg['text']=="/bye": ## bot2.sendMessage(chat_id,"You are disconnected. Click here: /chat%s to reconnect."%i['user2']) ## chat_list.remove(i) ## ## else: ## bot2.sendMessage(int(i['user2']), "/chat{} says: ".format(chat_id)) ## bot2.forwardMessage(int(i['user2']),chat_id,msg['message_id']) ## break if 'contact' in msg.keys(): if msg['contact']['user_id']==chat_id: id_phonedict[chat_id]=msg['contact']['phone_number'] bot.sendMessage(chat_id,"Verified! %s"%thumbsup) introMessage="You can choose to be an Orderer or an Orderee. An Orderer helps the Orderee to order food.\nWould like to be an Orderer or Orderee? %s"%sassy markup=InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="Orderer",callback_data="o1"), InlineKeyboardButton(text="Orderee",callback_data="o2")] ]) bot.sendMessage(chat_id,introMessage,reply_markup=markup) else: bot.sendMessage(chat_id,"Eh who you trying to bluff?! Thats not your phone number!") verify(chat_id) elif 'successful_payment' in msg.keys(): bot.sendMessage(chat_id, 'Wah you damn brudder. Thanks for the Kopi! Limpeh will remember you forever!!') bot.sendSticker(chat_id, 'CAADAgADJQADyIsGAAGoEDksgR1WpAI') elif content_type=="text": if msg['text']=="/start": verify(chat_id) elif msg['text'].startswith("/broadcast"): if chat_id==243431792: count=0 #count how many users in each batch to prevent spam for i in id_phonedict: if count>=20: time.sleep(1) count=0 else: count+=1 bot.sendMessage(i,msg) elif msg['text']=="/logs": if chat_id==243431792: print(id_phonedict) print(orderee_list) print(all_list) elif msg['text']=="/stop": for i in all_list: if i['userid']==str(chat_id): all_list.remove(i) bot.sendMessage(chat_id,"Done! You won't receive anymore orders. However, you may still accept existing orders!") elif msg['text']=="/report": bot.sendMessage(chat_id,"If reporting user, let me know the user name, mobile number and the reason below.",reply_markup=ForceReply()) ## elif msg['text'].startswith("/chat"): ## for i in chat_list: ## if i['user1']==str(chat_id): ## temp="/chat"+str(i['user2']) ## chat_list.remove(i) ## bot2.sendMessage(chat_id,"Previous chat was closed. Click here: %s to re-enter chat."%temp) ## other_id=msg['text'][5:] ## chat_pair={} ## chat_pair['user1']=str(chat_id) ## chat_pair['user2']=str(other_id) ## chat_list.append(chat_pair) ## bot2.sendMessage(chat_id,"You are connected to {}. Click here: /bye to close.".format(chat_pair['user2'])) ## bot.sendMessage(chat_id, "You are connected. Click here to chat: @orderup_chatbot") elif msg['text']=="/status": o1_stall_1=0 o1_stall_2=0 o1_stall_3=0 o1_stall_4=0 o1_stall_5=0 o1_stall_6=0 o1_stall_7=0 o1_stall_8=0 o1_stall_9=0 o1_stall_10=0 o1_stall_11=0 o1_stall_12=0 o1_stall_13=0 o1_stall_14=0 ## o2_stall_1=0 ## o2_stall_2=0 ## o2_stall_3=0 ## o2_stall_4=0 ## o2_stall_5=0 ## o2_stall_6=0 ## o2_stall_7=0 ## o2_stall_8=0 ## o2_stall_9=0 ## o2_stall_10=0 ## o2_stall_11=0 ## o2_stall_12=0 ## o2_stall_13=0 ## o2_stall_14=0 for i in all_list: if i["stall"]=="1": o1_stall_1+=1 elif i["stall"]=="2": o1_stall_2+=1 elif i["stall"]=="3": o1_stall_3+=1 elif i["stall"]=="4": o1_stall_4+=1 elif i["stall"]=="5": o1_stall_5+=1 elif i["stall"]=="6": o1_stall_6+=1 elif i["stall"]=="7": o1_stall_7+=1 elif i["stall"]=="8": o1_stall_8+=1 elif i["stall"]=="9": o1_stall_9+=1 elif i["stall"]=="a": o1_stall_10+=1 elif i["stall"]=="b": o1_stall_11+=1 elif i["stall"]=="c": o1_stall_12+=1 elif i["stall"]=="d": o1_stall_13+=1 elif i["stall"]=="e": o1_stall_14+=1 ## for j in orderee_list: ## if j["options"][1]=="1": ## o2_stall_1+=1 ## elif j["options"][1]=="2": ## o2_stall_2+=1 ## elif j["options"][1]=="3": ## o2_stall_3+=1 ## elif j["options"][1]=="4": ## o2_stall_4+=1 ## elif j["options"][1]=="5": ## o2_stall_5+=1 ## elif j["options"][1]=="6": ## o2_stall_6+=1 ## elif j["options"][1]=="7": ## o2_stall_7+=1 ## elif j["options"][1]=="8": ## o2_stall_8+=1 ## elif j["options"][1]=="9": ## o2_stall_9+=1 ## elif j["options"][1]=="a": ## o2_stall_10+=1 ## elif j["options"][1]=="b": ## o2_stall_11+=1 ## elif j["options"][1]=="c": ## o2_stall_12+=1 ## elif j["options"][1]=="d": ## o2_stall_13+=1 ## elif j["options"][1]=="e": ## o2_stall_14+=1 message=("*Soya Milk*\nOrderer: {}\n*Fruit Juice*\nOrderer: {}\n*Chinese Food*\nOrderer: {}\n" "*Western Food*\nOrderer: {}\n*Chicken Rice*\nOrderer: {}\n*Japanese Food*\nOrderer: {}\n" "*Ramen Corner*\nOrderer: {}\n*Yong Tau Foo*\nOrderer: {}\n*Vegetarian Food*\nOrderer: {}\n" "*Fishball Noddles*\nOrderer: {}\n*Indian Food*\nOrderer: {}\n*Indonesian Food*\nOrderer: {}\n" "*Drinks and Snacks*\nOrderer: {}\n*McDonalds*\nOrderer: {}\n".format( o1_stall_1, o1_stall_2, o1_stall_3, o1_stall_4, o1_stall_5, o1_stall_6, o1_stall_7, o1_stall_8, o1_stall_9, o1_stall_10, o1_stall_11, o1_stall_12, o1_stall_13, o1_stall_14)) bot.sendMessage(chat_id,message,parse_mode="Markdown") elif msg['text']=="/orders": my_orderer_msg="---My orders for today---\n" #showing who your orderers my_orderee_msg="---What I'm ordering for others today---\n" #showing who you ordering for temp_num=0 for i in all_list: if str(chat_id) in i['orderees']: for k in orderee_list: if 'orderer' in k.keys() and str(k['orderer'])==i['userid']: temp_num+=1 my_orderer_msg+="{}) Orderer id: {}\nStall: {}\nOrder: {}\nTip: {}\n[CLICK HERE TO CHAT](tg://user?id={})\n\n".format(temp_num,i['userid'],i['stall'],k['order'],k['tip'],i['userid']) bot.sendMessage(chat_id,my_orderer_msg,parse_mode="Markdown") temp_num=0 for j in orderee_list: if 'orderer' in j.keys() and j['orderer']==chat_id: temp_num+=1 my_orderee_msg+="{}) Orderee id: {}\nStall: {}\nOrder: {}\nTip: {}\n[CLICK HERE TO CHAT](tg://user?id={})\n\n".format(temp_num,j['userid'],j['options'][1],j['order'],j['tip'],j['userid']) bot.sendMessage(chat_id,my_orderee_msg,parse_mode="Markdown") elif 'reply_to_message' in msg.keys(): if "Type your orders clearly below!" in msg['reply_to_message']['text']: if chat_id in temp_dict.keys(): orderee_info_dict=temp_dict[chat_id] orderee_info_dict['order']=msg['text'] temp_dict[chat_id]=orderee_info_dict ## for i in orderee_list: ## if str(chat_id) in i['userid'] and "order" not in i.keys(): ## i['order']=msg['text'] ## break bot.sendMessage(chat_id,"Type your tip amount! Pay your Orderer when you collect your food!",reply_markup=ForceReply()) elif "Type your tip amount! Pay your Orderer when you collect your food!" in msg['reply_to_message']['text']: if chat_id in temp_dict.keys(): orderee_info_dict=temp_dict[chat_id] orderee_info_dict['tip']=msg['text'] temp_dict[chat_id]=orderee_info_dict bot.sendMessage(chat_id, "Type a location to meet!",reply_markup=ForceReply()) elif "Type a location to meet!" in msg['reply_to_message']['text']: orderer_num_int=0 if chat_id in temp_dict.keys(): orderee_info_dict=temp_dict[chat_id] orderee_info_dict['location']=msg['text'] temp_options=orderee_info_dict['options'] temp_order=orderee_info_dict['order'] temp_tip=orderee_info_dict['tip'] temp_location=orderee_info_dict['location'] ## for i in orderee_list: ## if str(chat_id)in i['userid'] and "tip" not in i.keys(): ## i['tip']=msg['text'] ## temp_options=i['options'] ## temp_order=i['order'] ## temp_tip=i['tip'] ## break markup=InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="Accept",callback_data="A"+temp_options+str(chat_id))] ]) markup1=InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="Cancel",callback_data="C"+temp_options+str(chat_id))] ]) for j in all_list: if j['stall']==temp_options[1]: orderer_num_int+=1 bot.sendMessage(j["userid"],"Found an Orderee!\nOrder: {}\nTip: {}\nMeet: {}\nTo stop receiving: /stop".format(temp_order,temp_tip,temp_location),reply_markup=markup) message_with_inline_keyboard=None message_with_inline_keyboard=bot.sendMessage(chat_id, "{} orderers in the queue so far. Waiting for Orderers... {}".format(orderer_num_int,timer) ,reply_markup=markup1) orderee_info_dict['kmsg']=message_with_inline_keyboard orderee_list.append(orderee_info_dict) del temp_dict[chat_id] elif "If reporting user, let me know the user name, mobile number and the reason below." in msg['reply_to_message']['text']: bot.forwardMessage(243431792,chat_id,msg['message_id']) elif msg['text']=="/donate": bot.sendInvoice(chat_id, "Donation", "Buy me Kopi if you like this project and would like to see it improve!", payload='a-string-identifying-related-payment-messages-tuvwxyz', provider_token='350862534:LIVE:ODg0ZDRiYzU3ZmY1', start_parameter='abc', currency='SGD', prices=[ LabeledPrice(label='Kopi', amount=300)],photo_url='https://goo.gl/4Mv7he',photo_size=4096,photo_width=64,photo_height=64)
def on_chat_message(msg): # print('msg: ', msg) content_type, chat_type, chat_id = telepot.glance(msg) if content_type != 'text': bot.sendMessage(chat_id, 'آر یو کیدینگ می؟') return None # print('Chat:', content_type, chat_type, chat_id) command = msg['text'] # print(' Live Users: ', live_users, '\n', 'Live Requests: ', live_requests, '\n') if content_type != 'text': return None if command == '/show': markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='سایت شورا صنفی', url='http://shora.ce.sharif.edu/')], [InlineKeyboardButton(text='تاسیسات', callback_data='tasisat')], [InlineKeyboardButton(text='گمشده ها', callback_data='lost')], ]) global message_with_inline_keyboard message_with_inline_keyboard = bot.sendMessage(chat_id, 'منو', reply_markup=markup) return None if command == '/done': working_request = None working_request_index = -1 for req in live_requests: if req.chat.id == chat_id: working_request = req working_request_index = live_requests.index(working_request) break if working_request_index == -1: bot.sendMessage(chat_id, 'چیزی نگفتی که هنوز 🤔') return None if working_request.subject.item == '' or working_request.subject.place == '': bot.sendMessage(chat_id, 'مورد یا مکان رو هنوز مشخص نکردی 😁') return None shora_api.send_message( ShoraMessage(working_request.subject.item, working_request.subject.place, working_request.subject.more)) # commit new request live_requests.pop(working_request_index) live_users.remove(chat_id) bot.sendMessage( chat_id, 'مساله ی موردنظر شما ثبت شد' + '\n' + 'آیتم: ' + working_request.subject.item + '\n' + 'مکان: ' + working_request.subject.place + '\n' + 'توضیحات: ' + working_request.subject.more + '\n' + '😜') return None if command == '/cancel': if chat_id not in live_users: bot.sendMessage(chat_id, 'هنوز چیزی نگفتی 🤔') return None if chat_id in live_users: live_users.remove(chat_id) for req in live_requests: if req.chat.id == chat_id: live_requests.remove(req) bot.sendMessage(chat_id, 'حلله ✋🏻') break return None if command == '/content': # print('content') if chat_id not in live_users: bot.sendMessage(chat_id, 'هنوز چیزی نگفتی 🤔') return None for req in live_requests: if req.chat.id == chat_id: bot.sendMessage( chat_id, 'متن تا الان: ' + '\n' + 'آیتم: ' + req.subject.item + '\n' + 'مکان: ' + req.subject.place + '\n' + 'توضیحات: ' + req.subject.more + '\n' + '😜') return None chat = Chat(**msg['from']) chat_id = chat.id text = msg['text'] if chat_id in live_users: # print('Live User') working_request = None working_request_index = -1 for req in live_requests: if req.chat.id == chat_id: working_request = req working_request_index = live_requests.index(working_request) break if working_request is None: # print('working_request id None') working_request = Request(chat, Subject()) live_requests.append(working_request) working_request_index = len(live_requests) - 1 working_subject = working_request.subject if working_subject.item == '': # print('If 1') working_subject.item = text working_request.subject = working_subject live_requests[working_request_index] = working_request bot.sendMessage(chat_id, 'لطفا مکان را بفرمایید', reply_markup=ForceReply()) elif working_subject.place == '': # print('If 2') working_subject.place = text working_request.subject = working_subject live_requests[working_request_index] = working_request bot.sendMessage(chat_id, 'توضیحات بیشتر در صورت نیاز', reply_markup=ForceReply()) elif working_subject.more == '': # print('If 3') working_subject.more = text working_request.subject = working_subject live_requests.pop(working_request_index) live_users.remove(chat_id) shora_api.send_message( ShoraMessage(working_subject.item, working_subject.place, working_subject.more)) # commit new request bot.sendMessage( chat_id, 'مساله ی موردنظر شما ثبت شد' + '\n' + 'آیتم: ' + working_subject.item + '\n' + 'مکان: ' + working_subject.place + '\n' + 'توضیحات: ' + working_subject.more + '\n' + '😜') else: # print('Gazcher message') markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='سایت شورا صنفی', url='http://shora.ce.sharif.edu/')], [InlineKeyboardButton(text='تاسیسات', callback_data='tasisat')], [InlineKeyboardButton(text='گمشده ها', callback_data='lost')], ]) global message_with_inline_keyboard message_with_inline_keyboard = bot.sendMessage(chat_id, 'منو', reply_markup=markup)
def handle(self, msg): flavor = telepot.flavor(msg) global bot global events # print(msg) # chat message if flavor == 'chat': content_type, chat_type, chat_id = telepot.glance(msg) # print(content_type, chat_type, chat_id) if content_type == 'text': chat = Chat(**msg['from']) text_message = TextMessage(msg['text'], msg['message_id'], chat) if text_message.text == '/get_last_event': all_events = session.query(Event).all() if len(all_events) != 0: bot.sendMessage(chat.id, all_events[len(all_events) - 1].inform()) if text_message.text == '/add_event': events.append(Event(event_chat=chat)) bot.sendMessage(chat.id, '1. Tell me the name of the event in reply to this message', reply_markup=ForceReply()) if 'reply_to_message' in msg: main_chat = Chat(**msg['reply_to_message']['from']) main_message = TextMessage(msg['reply_to_message']['text'], msg['reply_to_message']['message_id'], main_chat) if '1.' in main_message.text: for e in events: if e.event_chat.id == chat.id: e.event_name = text_message.text break bot.sendMessage(chat.id, '2. Tell me the date of the event in reply to this message', reply_markup=ForceReply()) if '2.' in main_message.text: for e in events: if e.event_chat.id == chat.id: e.event_date = text_message.text break bot.sendMessage(chat.id, '3. Tell me the hour of the event in reply to this message', reply_markup=ForceReply()) if '3.' in main_message.text: for e in events: if e.event_chat.id == chat.id: e.event_hour = text_message.text break bot.sendMessage(chat.id, '4. Tell me the location of the event in reply to this message', reply_markup=ForceReply()) if '4.' in main_message.text: for e in events: if e.event_chat.id == chat.id: e.event_location = text_message.text break bot.sendMessage(chat.id, '5. Tell me the description (any links maybe)' ' of the event in reply to this message', reply_markup=ForceReply()) if '5.' in main_message.text: for e in events: if e.event_chat.id == chat.id: e.event_description = text_message.text session.add(e) session.commit() events.remove(e) break bot.sendMessage(chat.id, 'Congratulations, your event has been create. You can see the ' 'list of events using "/get_last_event" command')
def on_chat_message(msg): # print('msg: ', msg) content_type, chat_type, chat_id = telepot.glance(msg) if content_type != 'text': bot.sendMessage(chat_id, 'آر یو کیدینگ می؟') return None # print('Chat:', content_type, chat_type, chat_id) command = msg['text'] # print(' Live Users: ', live_users, '\n', 'Live Requests: ', live_requests, '\n') if content_type != 'text': return None if command == '/show': markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='سایت شورای صنفی', url='http://shora.ce.sharif.edu/')], [InlineKeyboardButton(text='تاسیسات', callback_data='tasisat')], [InlineKeyboardButton(text='گمشدهها', callback_data='lost')], ]) global message_with_inline_keyboard message_with_inline_keyboard = bot.sendMessage(chat_id, 'منو', reply_markup=markup) return None if command == '/done': working_request = None working_request_index = -1 for req in live_requests: if req.chat.id == chat_id: working_request = req working_request_index = live_requests.index(working_request) break if working_request_index == -1: # bot.sendMessage(chat_id, 'چیزی نگفتی که هنوز 🤔') return None if working_request.subject.item == '' or working_request.subject.place == '': bot.sendMessage(chat_id, 'مورد یا مکان رو هنوز مشخص نکردی 😁') return None api_success, api_message = shora_api.send_message(ShoraMessage(working_request.subject.item, working_request.subject.place, working_request.subject.more)) # commit new request live_requests.pop(working_request_index) live_users.remove(chat_id) bot.sendMessage(chat_id, 'مسالهٔ موردنظر شما ثبت شد' + '\n' + 'آیتم: ' + working_request.subject.item + '\n' + 'مکان: ' + working_request.subject.place + '\n' + 'توضیحات: ' + working_request.subject.more + '\n') if api_success: logger.info("New issue submitted " + working_request.subject) else: logger.error("Issue could not be submitted " + working_request.subject + " with error message: " + api_message) if working_request.subject.type == 1: bot.sendMessage(chat_id, 'ما پیگیر مسالهٔ ثبت شده شما هستیم و آن را در لیست کارهای بخش تاسیسات قرار خواهیم داد.') elif working_request.subject.type == 2: bot.sendMessage(chat_id, 'امیدواریم وسیله گم شده ی خود را هر چه زودتر پیدا کنید.') return None if command == '/cancel': if chat_id not in live_users: bot.sendMessage(chat_id, 'هنوز چیزی نگفتی 🤔') return None if chat_id in live_users: live_users.remove(chat_id) for req in live_requests: if req.chat.id == chat_id: live_requests.remove(req) bot.sendMessage(chat_id, 'حلله ✋🏻') break return None if command == '/content': # print('content') if chat_id not in live_users: bot.sendMessage(chat_id, 'هنوز چیزی نگفتی 🤔') return None for req in live_requests: if req.chat.id == chat_id: bot.sendMessage(chat_id, 'متن تا الان: ' + '\n' + 'آیتم: ' + req.subject.item + '\n' + 'مکان: ' + req.subject.place + '\n' + 'توضیحات: ' + req.subject.more + '\n') return None chat = Chat(**msg['from']) chat_id = chat.id text = msg['text'] if chat_id in live_users: # print('Live User') working_request = None working_request_index = -1 for req in live_requests: if req.chat.id == chat_id: working_request = req working_request_index = live_requests.index(working_request) break if working_request is None: # print('working_request id None') working_request = Request(chat, Subject()) live_requests.append(working_request) working_request_index = len(live_requests) - 1 working_subject = working_request.subject # a little hard coded, i know if 'reply_to_message' in msg: if 'گزارش' in msg['reply_to_message']['text']: working_subject.type = 1 elif 'گم' in msg['reply_to_message']['text']: working_subject.type = 2 if working_subject.item == '': # print('If 1') working_subject.item = text working_request.subject = working_subject live_requests[working_request_index] = working_request bot.sendMessage(chat_id, 'لطفا محل موردنظر را بفرمایید', reply_markup=ForceReply()) elif working_subject.place == '': # print('If 2') working_subject.place = text working_request.subject = working_subject live_requests[working_request_index] = working_request bot.sendMessage(chat_id, 'توضیحات بیشتر (اگر نیاز به توضیح ندارد /done را بزنید)', reply_markup=ForceReply()) elif working_subject.more == '': # print('If 3') working_subject.more = text working_request.subject = working_subject live_requests.pop(working_request_index) live_users.remove(chat_id) api_success, api_message = shora_api.send_message(ShoraMessage(working_subject.item, working_subject.place, working_subject.more)) if api_success: logger.info("New issue submitted " + working_request.subject) else: logger.error("Issue could not be submitted " + working_request.subject + " with error message: " + api_message) # commit new request bot.sendMessage(chat_id, 'مسالهٔ موردنظر شما ثبت شد' + '\n' + 'آیتم: ' + working_subject.item + '\n' + 'مکان: ' + working_subject.place + '\n' + 'توضیحات: ' + working_subject.more) if working_subject.type == 1: bot.sendMessage(chat_id, 'ما پیگیر مسالهٔ ثبت شده شما هستیم و آن را در لیست کارهای بخش تاسیسات قرار خواهیم داد.') elif working_subject.type == 2: bot.sendMessage(chat_id, 'امیدواریم وسیله گم شده ی خود را هر چه زودتر پیدا کنید.') else: markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='سایت شورا صنفی', url='http://shora.ce.sharif.edu/')], [InlineKeyboardButton(text='تاسیسات', callback_data='tasisat')], [InlineKeyboardButton(text='گمشده ها', callback_data='lost')], ]) global message_with_inline_keyboard message_with_inline_keyboard = bot.sendMessage(chat_id, 'منو', reply_markup=markup)
def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) if 'reply_to_message' in msg:#it's a reply reply = replyhandler.handle(msg) bot.sendMessage(chat_id, reply) elif msg['text'].strip() == '/klasemen': reply = 'KLASEMEN LIGA BADR 2017\n' reply += '=======================\n' players = herokudb.getStandings() reply += '' count = 1 for player in players: reply += "{}. {} {}-{}-{} {}\n".format( count, player[0], player[1], player[2], player[3], player[4]) count += 1 reply += '=======================\n' reply += ('Klasemen di atas belum menggunakan tie break.' ' Versi lebih akurat cek: http://challonge.com/badrleague') bot.sendMessage(chat_id, reply) elif msg['text'].strip() == '/start' or msg['text'].strip() == '/help': reply = "BADR(o)BOT v0.2.3\n" reply += "Command yg tersedia:\n" reply += "/matchinfo - melihat hasil/jadwal tanding player\n" reply += "/klasemen - melihat klasemen saat ini\n" reply += "/teamhistory - melihat histori tim yg digunakan player\n" reply += "/updateskor - khusus admin (@yahyaman)\n\n" reply += "Coming soon:\n" reply += "(belum ada - silakan request)" bot.sendMessage(chat_id, reply) elif msg['text'].strip() == '/updateskor': reply = 'Command ini khusus Admin! Situ siapa? :p' force = None if msg['from']['id'] == ADMIN_ID: reply = 'Update skor dgn membalas chat ini:\n' reply += 'player1 tim1 skor1 player2 tim2 skor2\n' reply += 'Contoh:\n' reply += 'yahya juve 2 amri chelsea 1' force = ForceReply(force_reply=True, selective=True) bot.sendMessage(chat_id, reply, reply_to_message_id=msg['message_id'], reply_markup=force) elif msg['text'].strip() == '/teamhistory': reply = 'Pilih player:' players = herokudb.getPlayerList() count = 0 buttons = [] btn_row = [] for player in players: count += 1 data = "history-" + str(player[0]) btn_row.append(InlineKeyboardButton(text=player[1], callback_data=data)) if count % 3 == 0: buttons.append(btn_row) btn_row = [] #add last btns if present if len(btn_row) > 0: buttons.append(btn_row) keyboard = InlineKeyboardMarkup(inline_keyboard=buttons) bot.sendMessage(chat_id, reply, reply_markup=keyboard) elif msg['text'].strip() == '/matchinfo': reply = 'Pilih player:' players = herokudb.getPlayerList() buttons = helper.buildPlayerListButtons('match') keyboard = InlineKeyboardMarkup(inline_keyboard=buttons) bot.sendMessage(chat_id, reply, reply_markup=keyboard) else: bot.sendMessage(chat_id, "On progress!")
def on_chat_message(msg): 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'][0:].lower() # bot.sendMessage(chat_id, 'This is noooooot finnal noot wooorking keyboard', reply_markup=ReplyKeyboardMarkup( # keyboard=[ # [KeyboardButton(text="🗓️ Current Weather 🗓️"), KeyboardButton(text="📅 Weekly Weather 📅"), # KeyboardButton(text="🔧 Settings 🔧")] # ] # , resize_keyboard=True)) if command == '/start': markup = ReplyKeyboardMarkup(keyboard=[ [ KeyboardButton(text='s'), KeyboardButton(text='📅 Weekly Weather 📅') ], [KeyboardButton(text='🔧 Settings 🔧')], ]) bot.sendMessage(chat_id, 'Custom keyboard with various buttons', reply_markup=markup) elif command == 's': markup = ReplyKeyboardMarkup( keyboard=[[KeyboardButton( text='📍 Last location 📍' )], [KeyboardButton( text='➕ New Location ➕' )], [KeyboardButton(text='My Location', request_location=True)]]) bot.sendMessage(chat_id, 'Custom keyboard with various buttons', reply_markup=markup) elif command == 'i': markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='Telegram URL', url='https://core.telegram.org/')], [ InlineKeyboardButton(text='Callback - show notification', callback_data='notification') ], [dict(text='Callback - show alert', callback_data='alert')], [ InlineKeyboardButton(text='Callback - edit message', callback_data='edit') ], [ dict(text='Switch to using bot inline', switch_inline_query='initial query') ], ]) global message_with_inline_keyboard message_with_inline_keyboard = bot.sendMessage( chat_id, 'Inline keyboard with various buttons', reply_markup=markup) elif command == 'h': markup = ReplyKeyboardRemove() bot.sendMessage(chat_id, 'Hide custom keyboard', reply_markup=markup) elif command == 'f': markup = ForceReply() bot.sendMessage(chat_id, 'Force reply', reply_markup=markup)
def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) try: a = msg['chat']['title'] except: a = msg['chat']['id'] b = content_type c = chat_type d = chat_id texto = msg['text'] nome = msg['from']['first_name'] id = msg['from']['id'] send = bot.sendMessage from_id = msg['from']['id'] chat_id = msg['chat']['id'] master = msg['from']['id'] reply_msg = "reply_to_message_id=msg['message_id']" txt = msg['text'].split(' ') message = msg['text'].split() len_msg = len(message) msg_id = msg['message_id'] M = "Markdown" print(msg['text'], msg['chat']['id']) ############################# #COMANDOS ############################# if texto == '/menu': markup = ReplyKeyboardMarkup(keyboard=[ ['OCULTAR', KeyboardButton(text='✌ Meu Canal ')], [ dict(text='INFO', callback_data='info'), KeyboardButton(text='GITHUB') ], ]) bot.sendMessage(chat_id, 'Menú extra!', reply_markup=markup) elif txt[0].lower() == '/go': if (from_id == 684842099): ####coloque seu-id if len_msg > 1: texto = msg[u'text'].split(' ', 1)[1] bot.sendMessage(chat_id, 'σk, vσu єnvíαr....') try: bot.sendMessage(-1001224597403, texto, parse_mode="Markdown") except: try: bot.sendMessage(-1001224597403, texto) except: bot.sendMessage( chat_id, "αlgσ єѕtα ímpєdíndσ quє єu єnvíє, pσr fαvσr vєrífíquє...", reply_to_message_id=msg["message_id"]) bot.sendMessage(chat_id, 'mєnѕαgєm єnvíαdα!', reply_to_message_id=msg["message_id"]) elif texto == "✌ Meu Canal ": markup = ReplyKeyboardMarkup(keyboard=[ ['OCULTAR', KeyboardButton(text='✌ Meu Canal ')], [dict(text='INFO')], ]) bot.sendMessage(chat_id, '[{}](telegram.me/{})'.format( 'Robo taylor', 'odouspam', ), parse_mode=M, disable_web_page_preview=True, reply_markup=markup, reply_to_message_id=msg_id) elif texto == 'INFO': a = bot.getMe() n = a['first_name'] u = a['username'] bot.sendMessage(chat_id, ''' 🤖Informações do bot: *________________________* bot: {} username: {} *_________* [Criador](https://telegram.me/Odouspam) '''.format(n, u), parse_mode=M) elif texto == '/chat_id': bot.sendMessage(chat_id, chat_id) elif txt[0] == '/adicione': if (from_id == 684842099) or (from_id == 1000660479): if len_msg > 1: texto = msg[u'text'].split(' ', 1)[1] try: arq = open('/root/lista.txt', 'a') except: arq = open('/root/lista.txt', 'w') arq.write('• ' + texto + '\n') bot.sendMessage(chat_id, '_Lista Atualizada!_', parse_mode="Markdown") arq.close() else: bot.sendMessage(chat_id, 'pєrmíѕѕãσ nєgαdα', reply_to_message_id=msg['message_id']) elif texto == '/lista': if (msg['chat']['type'] == 'private'): try: arq = open('/root/lista.txt', 'r') except: bot.sendMessage(chat_id, 'ѕєm ínfσrmαçõєѕ dєfínídαѕ...', parse_mode="Markdown") texto = arq.read() line = msg['chat']['id'] regras = [chat_id, texto] id = regras[0] arq.close() for id in texto: bot.sendMessage(chat_id, ''' *Lista de canais disponíveis*📖 {} _deseja adicionar seu canal na lista? fale com_ @paulo6'''.format(texto), parse_mode="Markdown") break else: bot.sendMessage(chat_id, 'Comando apenas para privado..', reply_to_message_id=msg['message_id']) elif texto == '/start': bot.sendMessage( chat_id, 'Ok! Vamos começar!, aguenta só um pouquinho que ja vou te passar o menú...' ) time.sleep(2) markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='🔧suporte', url='https://telegram.me/Odouspam')], [InlineKeyboardButton(text='📃status', callback_data='n')] + [InlineKeyboardButton(text='⚙Comandos', callback_data='edit')] + [InlineKeyboardButton(text='ℹinfo', callback_data='info')] ]) global message_with_inline_keyboard message_with_inline_keyboard = bot.sendMessage( chat_id, 'Oin! prazer *{}*✌😄!\n`sou o` *{}*!\n\n`você pode ultilizar meus` *comandos*, `para conhecê-los, basta clicar no botão...`' .format(nome, name), reply_markup=markup, parse_mode="Markdown") elif texto == 'OCULTAR': markup = ReplyKeyboardRemove() bot.sendMessage(chat_id, 'menu ocultado...', reply_markup=markup) elif texto == '/desbug': markup = ForceReply() bot.sendMessage(chat_id, 'Force reply', reply_markup=markup) elif msg['text'] == '/help': markup = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='📡✌ Meu Grupo ', url='https://t.me/joinchat/KNHccxT3lnygNpdyUvfHZw') ], [InlineKeyboardButton(text='👤Adms', callback_data='adm')] + [ InlineKeyboardButton(text='👥grupo', callback_data='edit') ], [ InlineKeyboardButton(text='🛠 remover usuário', callback_data='ban') ] + [ dict(text='Link🌐', callback_data='link') ], [InlineKeyboardButton(text='extras 🕹', callback_data='extra')] + [ InlineKeyboardButton(text='📝Sobre o grupo', callback_data='sobre') ], [InlineKeyboardButton(text='⚙DEVS', callback_data='dev')]]) global message_with_inline_keyboard mark = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Iniciar conversa👤', url='https://telegram.me/{}?start'.format(config.user)) ]]) try: message_with_inline_keyboard = bot.sendMessage( from_id, """ Deixa eu te fala, você pode entrar em contato com a minha equipe, a (Equipe Sk)[t.me/ListaSk], lá eles oferecem suporte rsrs.""" .format(msg['from']['first_name']), reply_markup=markup, parse_mode="Markdown") except: bot.sendMessage( chat_id, 'Por favor inicie uma conversa privada primeiro e tente /help novamente', reply_markup=mark)
def command_broadcast(msg, msg_chat_id): markup = ForceReply() bot.sendMessage(msg_chat_id, 'Broadcast: inserire un messaggio da inviare.', reply_markup=markup)
async def on_chat_message(self, msg): await self._logmsg(msg) content_type, chat_type, chat_id = telepot.glance(msg) bot_me = await bot.getMe() username = bot_me['username'].replace(' ', '') try: fuser = await bot.getChatMember(chat_id, msg['from']['id']) except: fnick = "Channel Admin" fuserid = None else: fnick = fuser['user']['first_name'] try: fnick = fnick + ' ' + fuser['user']['last_name'] except: fnick = fnick try: fnick = fnick + "@" + fuser['user']['username'] except: fnick = fnick fuserid = str(fuser['user']['id']) if chat_type == 'private': if content_type != 'text': dre = await self.sender.sendMessage('麻煩給我一個阿拉伯數字.') log("[Debug] Raw sent data:" + str(dre)) return if msg['text'] == '/stop': dre = await self.sender.sendMessage('遊戲結束,炸彈是 %d' % self._answer) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('/start_game') log("[Debug] Raw sent data:" + str(dre)) clog('[Info] ' + fnick + ' (' + fuserid + ') has stopped the game.\n[Info] Game ended.') self.close() try: guess = int(msg['text']) except ValueError: dre = await self.sender.sendMessage('麻煩給我一個阿拉伯數字.') log("[Debug] Raw sent data:" + str(dre)) return # check the guess against the answer ... if guess != self._answer: # give a descriptive hint hint = self._hint(self._answer, guess, self._cmin, self._cmax) dre = await self.sender.sendMessage(hint) log("[Debug] Raw sent data:" + str(dre)) else: dre = await self.sender.sendDocument( \ 'http://i.imgur.com/vjrcTIy.gif', caption='Boom!') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('遊戲結束,您引爆了炸彈') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('/start_game') log("[Debug] Raw sent data:" + str(dre)) clog('[Info] ' + fnick + ' (' + fuserid + \ ') has gotten the bomb and exploded.\n[Info] Game ended.') self.close() elif chat_type == 'group' or chat_type == 'supergroup': try: reply_to = msg['reply_to_message']['from']['id'] except: if content_type != 'text': if content_type == 'left_chat_member': if msg['left_chat_member']['id'] == bot_me['id']: clog('[Info] Game ended.') self.close() else: if msg['text'] == '/stop' or msg[ 'text'] == '/stop@' + username: markup = ForceReply() dre = await self.sender.sendMessage( self._answer, reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) msg_idf = telepot.message_identifier(dre) await bot.deleteMessage(msg_idf) dre = await self.sender.sendMessage('遊戲結束,炸彈是 %d' % self._answer, \ reply_to_message_id=msg['message_id']) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('/start_game', reply_markup=None) log("[Debug] Raw sent data:" + str(dre)) clog('[Info] ' + fnick + ' (' + fuserid + ') in ' + msg['chat']['title'] + \ ' (' + str(chat_id) + ') has stopped the game.\n[Info] Game ended.') self.close() return else: if reply_to == bot_me['id']: if content_type != 'text': if content_type == 'left_chat_member': if msg['left_chat_member']['id'] == bot_me['id']: clog('[Info] Game ended.') self.close() else: markup = ForceReply() dre = await self.sender.sendMessage('麻煩給我一個阿拉伯數字.', \ reply_to_message_id=msg['message_id'], reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) return if msg['text'] == '/stop' or msg[ 'text'] == '/stop@' + username: markup = ForceReply() dre = await self.sender.sendMessage( self._answer, reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) msg_idf = telepot.message_identifier(dre) await bot.deleteMessage(msg_idf) dre = await self.sender.sendMessage( '遊戲結束,炸彈是 %d' % self._answer, reply_to_message_id=msg['message_id']) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('/start_game', reply_markup=None) log("[Debug] Raw sent data:" + str(dre)) clog('[Info] ' + fnick + ' (' + fuserid + ') in ' + msg['chat']['title'] + \ ' (' + str(chat_id) + ') has stopped the game.\n[Info] Game ended.') self.close() try: guess = int(msg['text']) except ValueError: markup = ForceReply() dre = await self.sender.sendMessage('麻煩給我一個阿拉伯數字.', \ reply_to_message_id=msg['message_id'], reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) return # check the guess against the answer ... if guess != self._answer: # give a descriptive hint hint = self._hint(self._answer, guess, self._cmin, self._cmax) markup = ForceReply() dre = await self.sender.sendMessage(hint, \ reply_to_message_id=msg['message_id'], reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) else: markup = ForceReply() dre = await self.sender.sendMessage( self._answer, reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) msg_idf = telepot.message_identifier(dre) await bot.deleteMessage(msg_idf) dre = await self.sender.sendDocument('http://i.imgur.com/vjrcTIy.gif', \ caption='Boom!', reply_to_message_id=msg['message_id']) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('遊戲結束,您引爆了炸彈', \ reply_to_message_id=msg['message_id']) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('/start_game', reply_markup=None) log("[Debug] Raw sent data:" + str(dre)) clog('[Info] ' + fnick + ' (' + fuserid + ') in ' + msg['chat']['title'] + ' (' + \ str(chat_id) + ') has gotten the bomb and exploded.\n[Info] Game ended.') self.close() else: if content_type == 'text': if msg['text'] == '/stop' or msg[ 'text'] == '/stop@' + username: markup = ForceReply() dre = await self.sender.sendMessage( self._answer, reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) msg_idf = telepot.message_identifier(dre) await bot.deleteMessage(msg_idf) dre = await self.sender.sendMessage('遊戲結束,炸彈是 %d' % self._answer, \ reply_to_message_id=msg['message_id']) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage( '/start_game', reply_markup=None) log("[Debug] Raw sent data:" + str(dre)) clog('[Info] ' + fnick + ' (' + fuserid + ') in ' + msg['chat']['title'] + \ ' (' + str(chat_id) + ') has stopped the game.\n[Info] Game ended.') self.close()
async def open(self, initial_msg, seed): await self._logmsg(initial_msg) content_type, chat_type, chat_id = telepot.glance(initial_msg) bot_me = await bot.getMe() username = bot_me['username'].replace(' ', '') try: print('[EDIT][' + str(initial_msg['edit_date']) + ']:' + \ str(initial_msg['message_id']) + '-->' + initial_msg['text']) except: pass else: self.close() return try: fuser = await bot.getChatMember(chat_id, initial_msg['from']['id']) except: fnick = "Channel Admin" fuserid = None else: fnick = fuser['user']['first_name'] try: fnick = fnick + ' ' + fuser['user']['last_name'] except: fnick = fnick try: fnick = fnick + "@" + fuser['user']['username'] except: fnick = fnick fuserid = str(fuser['user']['id']) if chat_type == 'private': if content_type == 'text': if initial_msg['text'] == '/start_game': clog('[Info] ' + fnick + '(' + fuserid + \ ') has started a game with the bomb ' + str(self._answer)) dre = await self.sender.sendMessage('遊戲開始!請猜一個範圍內的數字') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('當猜中數字時就會爆炸,你只有 ' + str(Timeout) + ' 秒') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage( str(self._cmin) + ' - ' + str(self._cmax)) log("[Debug] Raw sent data:" + str(dre)) return True # prevent on_message() from being called on the initial message elif initial_msg['text'] == '/start': dre = await self.sender.sendMessage('歡迎使用炸彈數字') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('使用 /start_game 開始一個遊戲' ) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('一次回答的時間只有 ' + str(Timeout) + ' 秒') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('當您猜中數字,就會爆炸') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage( '遊戲中可使用 /stop 強制停止目前的遊戲') log("[Debug] Raw sent data:" + str(dre)) self.close() return else: dre = await self.sender.sendMessage('/start_game') log("[Debug] Raw sent data:" + str(dre)) self.close() return else: await self.sender.sendMessage('/start_game') self.close() return elif chat_type == 'group' or chat_type == 'supergroup': if content_type == 'text': if initial_msg['text'] == '/start_game' or \ initial_msg['text'] == '/start_game@' + username: clog('[Info] ' + fnick + '(' + fuserid + ') in ' + initial_msg['chat']['title'] + \ ' (' + str(chat_id) + ') has started a group game with the bomb ' + \ str(self._answer)) dre = await self.sender.sendMessage('遊戲開始!請猜一個範圍內的數字', \ reply_to_message_id=initial_msg['message_id']) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('當猜中數字時就會爆炸,你只有 ' + str(Timeout) + ' 秒') log("[Debug] Raw sent data:" + str(dre)) markup = ForceReply() dre = await self.sender.sendMessage(str(self._cmin) + ' - ' + str(self._cmax), \ reply_markup=markup) log("[Debug] Raw sent data:" + str(dre)) return True else: self.close() return elif content_type == 'new_chat_member': if initial_msg['new_chat_member']['id'] == bot_me['id']: dre = await self.sender.sendMessage('歡迎使用炸彈數字') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('使用 /start_game 開始一個遊戲' ) log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('群組模式中,Bot只會受理回復他的信息') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('一次回答的時間只有 ' + str(Timeout) + ' 秒') log("[Debug] Raw sent data:" + str(dre)) dre = await self.sender.sendMessage('當有人猜中數字,就會爆炸') log("[Debug] Raw sent data:" + str(dre)) self.close() return else: self.close() return return True # prevent on_message() from being called on the initial message
def _received_msg(self, new_msg): uid = new_msg["message"]["chat"]["id"] pesan = new_msg["message"].get("text") if pesan: for count, msg in enumerate(MESSAGES_NOW): if msg["uid"] == uid: # Delete element if user reply MESSAGES_NOW.pop(count) delete = msg["identifier"] ident = telepot.message_identifier(delete) bot.deleteMessage(ident) if str(uid) in str(self.__position): for index, element in enumerate(self.__position): if uid == element["uid"]: if element["position"] == "dl": tipe = "dl" self.__position.pop(index) if element["position"] == "joox": tipe = "joox" self.__position.pop(index) if element["position"] == "yt": self.__position.pop(index) try: a = requests.get(pesan).text judul = re.findall("<title>(.*?)</title>", a)[0].replace( " - YouTube", "") judul = "_".join([ i for i in re.findall("\w*", judul) if i != "" ]) return self.download(uid, pesan, judul, ytlink=True) except Exception as err: print(err) return err self._select_song(uid, pesan, tipe) else: if pesan.startswith("/dl"): query = pesan.split(" ", maxsplit=1) if len(query) == 1: markup = ForceReply(selective=False) pesan = "Ok, berikan saya query lagu yang mau dicari" bot.sendMessage(uid, pesan, reply_markup=markup) self.__position.append(dict(uid=uid, position="dl")) else: self._select_song(uid, query[1], "dl") elif pesan.startswith("/yt"): url = pesan.split(" ", maxsplit=1) if len(url) == 1: markup = ForceReply(selective=False) pesan = "Ok, berikan saya link youtubenya" bot.sendMessage(uid, pesan, reply_markup=markup) self.__position.append(dict(uid=uid, position="yt")) else: try: a = requests.get(url[1]).text judul = re.findall("<title>(.*?)</title>", a)[0].replace(" - YouTube", "") judul = "_".join([ i for i in re.findall("\w*", judul) if i != "" ]) self.download(uid, url[1], judul=judul, ytlink=True) except Exception as err: print(err) return err elif pesan.startswith("/joox"): query = pesan.split(" ", maxsplit=1) if len(query) == 1: markup = ForceReply(selective=False) pesan = "Ok, berikan saya query yang mau dicari" bot.sendMessage(uid, pesan, reply_markup=markup) self.__position.append(dict(uid=uid, position="joox")) else: self._select_song(uid, query[1], "joox") elif pesan.startswith("/start"): pesan = "Penggunaan\n" pesan += "/dl [query]\n" pesan += "Contoh:\n" pesan += " /dl Noah\n\n" pesan += "/yt [url]\n" pesan += "Contoh:\n\t" pesan += " /yt https://youtu.be/y6e_kztXG04" bot.sendMessage(uid, pesan, disable_web_page_preview=True) else: pesan = "Pesan tidak dikenali\n" pesan += "/dl [query]\n" pesan += "Contoh:\n" pesan += " /dl Noah\n\n" pesan += "/yt [url]\n" pesan += "Contoh:\n\t" pesan += " /yt https://youtu.be/y6e_kztXG04" bot.sendMessage(uid, pesan, disable_web_page_preview=True) else: bot.sendMessage(uid, "Bot hanya mengenali pesan yang berupa text ")
def on_chat_message(self, msg): to = msg['from']['id'] try: output = [] wc = Wordchar.get(Wordchar.wordchar == msg['text']) explain = wc.explains[0] output.append("*%s*: %s, %s" % (msg['text'], explain.pinyin, explain.explain)) if wc.english: output.append("English: %s" % wc.english.split(',')[0].strip()) if wc.tongyi: output.append("同义词: %s" % wc.tongyi.split(',')[0].strip()) if wc.fanyi: output.append("反义词: %s" % wc.fanyi.split(',')[0].strip()) if wc.bianxi: output.append("辨析: %s" % wc.bianxi.split(',')[0].strip()) if wc.url: output.append("Link: %s" % wc.url) c = '\n'.join(output) #send writing gif if wc.writing: self.sendDocument(to, ('a.gif', io.BytesIO(wc.writing))) except DoesNotExist: c = None markup2 = ForceReply() markup = ReplyKeyboardMarkup(keyboard=[ ['上', '下', '左', '右'], ]) #send basic information if c: #self.sendMessage(to, c, parse_mode='markdown', # disable_web_page_preview=True) pass #send full explaination # output = [] # for e in wc.explains.order_by(Explain.order): # output.append("%s, %s, %s" % (e.pinyin, e.explain, e.examples)) # self.sendMessage(to, '\n'.join(output)) #send voice wcl = [] pl = [] if not c: for w in jieba.posseg.cut(msg['text']): try: wcl.append(Wordchar.get(Wordchar.wordchar == w.word)) except DoesNotExist: #collect one by one self.sendMessage( to, 'Give me Chinese words you want to learn...') return #for c in w.word: # wcl.append(Wordchar.get(Wordchar.wordchar==c)) pinyin = '/'.join([w.explains[0].pinyin for w in wcl]) else: pinyin = explain.pinyin if c: py_str = c else: py_str = ' '.join(pinyin.split('/')) playtime = 0 for pinyin in pinyin.split('/'): p = Pronounce.get(Pronounce.pinyin == pinyin) pl.append(p) f = OggVorbis(io.BytesIO(p.mp3)) playtime += f.info.length py = b''.join([p.mp3 for p in pl]) self.sendVoice(to, io.BytesIO(py), duration=playtime, caption=py_str)
async def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) print(content_type) print( 'Chat:', content_type, chat_type, chat_id, datetime.datetime.fromtimestamp(int( msg['date'])).strftime('(%Y-%m-%d %H:%M:%S)')) if content_type != 'text': if content_type == 'sticker': print(msg['sticker'].get('file_id')) elif content_type == 'text': print(msg['text'].encode('unicode-escape').decode('ascii')) f = open('bd.txt', 'r') if msg['text'].lower() == '/start': if f.read(1) == '1': dintro = ' Приветствуем в Пустоши. Ты просыпаешься, сразу проверяешь обрез под подушкой. Внимательно осматриваешь местность из окна. Вчера ты нашёл этот заброшенный домик для ночлега, но долго тут оставаться не вариант, ведь запасы воды и еды не бесконечные. Выбери действие:' f = open('bd.txt', 'w') img1 = open('img1.jpg', 'rb') markup = ReplyKeyboardMarkup( keyboard=[['Осмотреть шкафчики в поиске провизии'], ['Не тратить время на поиски и выйти']], resize_keyboard=True) await bot.sendMessage( chat_id, 'Над радиационными тучами встаёт солнце...') await bot.sendPhoto( chat_id, photo=img1, caption='Здравствуй, %s!' % msg["from"].get("first_name") + dintro, reply_markup=markup) f = open('bd.txt', 'w') f.close() img1.close() #=============Основной цикл игры========== tick() #========================================= else: print(msg["from"].get("last_name")) if msg["from"].get("username") == "None": await bot.sendMessage( chat_id, "Эй, %s!" % msg["from"].get("first_name") + ' Ты ведь уже начал игру.. Хуле старт клацаешь?\U0001F44A' ) else: await bot.sendMessage( chat_id, "Эй, %s!" % msg["from"].get("username") + ' Ты ведь уже начал игру.. Хуле старт клацаешь?\U0001F44A' ) #================================================== command = msg['text'].lower() if command == 'c' or msg['text'] == '\U0001f519 Назад': markup = ReplyKeyboardMarkup(keyboard=[[ '/start', '/restart', '/stats' ], ['admin', '\U0001f3de Поселение', '\U0001f3ec Магазин']], resize_keyboard=True) await bot.sendMessage(chat_id, 'Выбери действие: ', reply_markup=markup) elif msg['text'] == 'Ромочка': chat_id = '624737506' while True: await bot.sendMessage(chat_id, msg['text']) #============Cюжетка============================================= elif msg['text'] == 'Осмотреть шкафчики в поиске провизии': img2 = open('img2.jpg', 'rb') markup = ReplyKeyboardMarkup( keyboard=[['Засунуть руку подальше'], ['Взять первые банки и уйти']], resize_keyboard=True) await bot.sendMessage(chat_id, 'Надеюсь, будет чем подкрепиться...') await bot.sendPhoto( chat_id, photo=img2, caption= 'Ты открываешь дверцу шкафа и видишь кучу банок с стёртыми названиями.', reply_markup=markup) img2.close() elif msg['text'] == 'Засунуть руку подальше': markup = ReplyKeyboardMarkup( keyboard=[['Сложить пожитки в рюкзак и уйти']], resize_keyboard=True) await bot.sendMessage( chat_id, 'Ничего полезного.. Срок годности некоторых продуктов закончился много лет назад, надо уходить.', reply_markup=markup) elif msg['text'] == 'Взять первые банки и уйти' or msg[ 'text'] == 'Сложить пожитки в рюкзак и уйти': img5 = open('img5.jpg', 'rb') markup = ReplyKeyboardMarkup(keyboard=[['Продолжить движение']], resize_keyboard=True) await bot.sendMessage( chat_id, 'Расставив найденное на стол, ты начинаешь проводить ревизию...' ) await bot.sendPhoto( chat_id, photo=img5, caption= '\U0001f392 Рюкзак:\n\n+2 Консервы "Говяжий дошик"\n+1 Бутылка чистой воды ', reply_markup=markup) img5.close() elif msg['text'] == 'Не тратить время на поиски и выйти' or msg[ 'text'] == 'Продолжить движение': img3 = open('img3.jpg', 'rb') markup = ReplyKeyboardMarkup( keyboard=[['Подойти ближе, чтоб разглядеть врага'], ['Потихоньку отойти назад и убежать']], resize_keyboard=True) await bot.sendMessage( chat_id, 'Вещи собраны и герой потихоньку двигается в сторону двери...') await bot.sendPhoto( chat_id, photo=img3, caption= 'Просторы пустоши были невероятно красивые. В этой атмосфере постапокалиптического утра чуствовалось что-то загадочное. Твоё внимание привлёк шелест кустов в ста метрах и рука опустилась на спусковые крючки обреза.', reply_markup=markup) img3.close() #================================================================ elif msg['text'].lower() == 'admin': print(msg['from'].get('username')) if msg['from'].get('username') == 'xXZyzzXx': markup = ReplyKeyboardMarkup( keyboard=[['+exp', '+Деньги', 'Бан'], ['Код', 'Hide=h']], resize_keyboard=True) await bot.sendMessage(chat_id, 'Выбери действие: ', reply_markup=markup) #==============Поселение==== elif msg['text'] == '\U0001f3de Поселение' or msg[ 'text'] == '\u2b05\ufe0f Назад': markup = ReplyKeyboardMarkup(keyboard=[[ '\U0001f3e1 Участок', '\U0001f417 Животные', '\U0001f6e0 Крафт' ], [ '\U0001f527 Улучшения', '\U0001f3d7 Строения', '\U0001f519 Назад' ]], resize_keyboard=True) await bot.sendMessage( chat_id, 'Добро пожаловать в Ваше поселение! Дела пока идут хорошо..', reply_markup=markup) elif msg['text'] == '\U0001f3e1 Участок': markup = ReplyKeyboardMarkup(keyboard=[['\u2b05\ufe0f Назад']], resize_keyboard=True) await bot.sendMessage( chat_id, 'На участке временно пусто, найдите зерна а так же постройте грядки в разделе "Строения"', reply_markup=markup) elif msg['text'] == '\U0001f417 Животные': markup = ReplyKeyboardMarkup(keyboard=[['\u2b05\ufe0f Назад']], resize_keyboard=True) await bot.sendMessage(chat_id, 'В загоне сейчас ' + str(config.animal) + ' животных', reply_markup=markup) elif msg['text'] == '\U0001f6e0 Крафт': markup = ReplyKeyboardMarkup(keyboard=[['\u2b05\ufe0f Назад']], resize_keyboard=True) await bot.sendMessage( chat_id, 'Станок не готов, для постройки необходимо 20 ед. дерева! У тебя ' + str(config.wood) + ' ед. дерева.', reply_markup=markup) elif msg['text'] == '\U0001f527 Улучшения': markup = ReplyKeyboardMarkup(keyboard=[['\u2b05\ufe0f Назад']], resize_keyboard=True) await bot.sendMessage(chat_id, 'Временно нечего улучшать. Уходи..', reply_markup=markup) elif msg['text'] == '\U0001f3d7 Строения': markup = ReplyKeyboardMarkup(keyboard=[['\u2b05\ufe0f Назад']], resize_keyboard=True) await bot.sendMessage( chat_id, 'Возможность постройки открывается дальше по сюжету.', reply_markup=markup) #=================== elif msg['text'] == '/restart': f = open('bd.txt', 'w') f.write('1') elif msg['text'] == '/stats': await stats(chat_id, msg) elif msg['text'] == '+exp': config.exp += 10 print(config.exp) elif command == 'h': markup = ReplyKeyboardRemove() await bot.sendMessage(chat_id, 'Hide custom keyboard', reply_markup=markup) elif command == 'f': markup = ForceReply() await bot.sendMessage(chat_id, 'Хуле хочешь', reply_markup=markup) '''
def on_callback_query(msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') ## print('Callback Query:', query_id, from_id, query_data) if query_data=="o1" or query_data=="o2": keyboard=InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Soya Milk", callback_data="s1"+query_data), InlineKeyboardButton(text="Fruit Juice", callback_data="s2"+query_data)], [InlineKeyboardButton(text="Chinese Food", callback_data="s3"+query_data), InlineKeyboardButton(text="Western", callback_data="s4"+query_data)], [InlineKeyboardButton(text="Chicken Rice", callback_data="s5"+query_data), InlineKeyboardButton(text="Japanese", callback_data="s6"+query_data)], [InlineKeyboardButton(text="Ramen Corner", callback_data="s7"+query_data), InlineKeyboardButton(text="Yong Tau Foo", callback_data="s8"+query_data)], [InlineKeyboardButton(text="Vegetarian", callback_data="s9"+query_data), InlineKeyboardButton(text="Fishball Noodles", callback_data="sa"+query_data)], [InlineKeyboardButton(text="Indian Food", callback_data="sb"+query_data), InlineKeyboardButton(text="Indonesian Food", callback_data="sc"+query_data)], [InlineKeyboardButton(text="Drinks and Snacks", callback_data="sd"+query_data), InlineKeyboardButton(text="McDonald's", callback_data="se"+query_data)] ] ) if query_data=="o1": user_type_text="Orderer" message="Hi fellow %s! %s Please select the stall you are queuing for! %s"%(user_type_text,waiter,cook) else: user_type_text="Orderee" message="Hi fellow %s! Please select a stall! %s"%(user_type_text,cook) bot.sendMessage(from_id, message, reply_markup=keyboard) elif query_data[0]=="s" and query_data[3]=="2" and len(query_data)==4: orderee_info_dict={} orderee_info_dict['userid']=str(from_id) orderee_info_dict['options']=query_data orderee_info_dict['accepted']=0 try: orderee_info_dict['phone_number']=id_phonedict[from_id] except: bot.sendMessage(from_id,"Sorry we need you to verify again! {}".format(pray)) verify(from_id) else: ## orderee_list.append(orderee_info_dict) temp_dict[from_id]=(orderee_info_dict) bot.sendMessage(from_id, "Type your orders clearly below!",reply_markup=ForceReply()) elif query_data[0]=="s" and query_data[3]=="1": valid_queuer=True for i in all_list: if i['userid']==str(from_id) and i['stall']==str(query_data[1]): valid_queuer=False bot.sendMessage(from_id,"You are already an Orderer for this stall!") if valid_queuer==True: message_with_inline_keyboard=None orderer_info_dict={} orderer_info_dict['userid']=str(from_id) orderer_info_dict['stall']=query_data[1] try: orderer_info_dict['phone_number']=id_phonedict[from_id] except: bot.sendMessage(from_id, "Sorry we need you to verify again! {}".format(pray)) verify(from_id) else: orderer_info_dict['orderees']=[] markup=InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="Cancel",callback_data="Z"+orderer_info_dict['stall'])] ]) message_with_inline_keyboard=bot.sendMessage(from_id, "You are now an Orderer! %s Be patient while we connect you with Orderees!"%waiter,reply_markup=markup) orderer_info_dict['kmsg']=message_with_inline_keyboard all_list.append(orderer_info_dict) for i in orderee_list: if i["options"][1]==query_data[1]: temp_options=i['options'] temp_order=i['order'] temp_tip=i['tip'] temp_location=i['location'] markup1=InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="Accept",callback_data="A"+temp_options+str(from_id))] ]) bot.sendMessage(from_id,"Found an Orderee!\nOrder: {}\nTip: {}\nMeet: {}\nTo stop receiving: /stop".format(temp_order,temp_tip,temp_location),reply_markup=markup1) elif query_data[0]=="A": found_orderee=False for i in orderee_list: if i['userid']==query_data[5:] and i['options']==query_data[1:5] and i['accepted']==0: i['accepted']=1 temp=query_data[5:] i['orderer']=from_id found_orderee=True msg_idf=telepot.message_identifier(i['kmsg']) bot.editMessageReplyMarkup(msg_idf) break if found_orderee==True: for j in all_list: if j['userid']==str(from_id) and j['stall']==str(query_data[2]): j['orderees'].append(temp) msg_idf=telepot.message_identifier(j['kmsg']) bot.editMessageReplyMarkup(msg_idf) break bot.sendMessage(from_id,"Nice one la! {} See your orders here: /orders To chat with your Orderee, [CLICK HERE](tg://user?id={})".format(thumbsup,query_data[5:]),parse_mode="Markdown") bot.sendMessage(query_data[5:],"Wah swee la! {} Your order has been accepted! See your orders here: /orders To chat with your Orderer, [CLICK HERE](tg://user?id={})".format(thumbsup,from_id), parse_mode="Markdown") else: bot.sendMessage(from_id,"Someone already accepted the order!") elif query_data[0]=="C": for i in orderee_list: if i["userid"]==str(from_id) and i["options"]==str(query_data[1:5]): orderee_list.remove(i) bot.sendMessage(from_id,"Order cancelled!") elif query_data[0]=="Z": for i in all_list: if i["userid"]==str(from_id) and i["stall"]==query_data[1]: all_list.remove(i) bot.sendMessage(from_id,"Cancelled!") break