async def on_shipping_query(self, msg): query_id, from_id, invoice_payload = amanobot.glance( msg, flavor='shipping_query') print('Shipping query:') pprint(msg) await bot.answerShippingQuery( query_id, True, shipping_options=[ ShippingOption(id='fedex', title='FedEx', prices=[ LabeledPrice(label='Local', amount=345), LabeledPrice(label='International', amount=2345) ]), ShippingOption(id='dhl', title='DHL', prices=[ LabeledPrice(label='Local', amount=342), LabeledPrice(label='International', amount=1234) ]) ])
def on_callback_query(self, msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') if query_data != 'start': self._score[self._answer == int(query_data)] += 1 self._answer = self._show_next_question()
async def on_chat_message(msg): content_type, chat_type, chat_id = amanobot.glance(msg) print(content_type, chat_type, chat_id) if content_type != 'successful_payment': sent = await bot.sendInvoice( chat_id, "Nick's Hand Cream", "Keep a man's hand like a woman's", payload='a-string-identifying-related-payment-messages-tuvwxyz', provider_token=PAYMENT_PROVIDER_TOKEN, start_parameter='abc', currency='HKD', prices=[ LabeledPrice(label='One Case', amount=987), LabeledPrice(label='Package', amount=12) ], need_shipping_address=True, is_flexible=True) # required for shipping query # 'Pay' button appears automatically pprint(sent) print(Invoice(**sent['invoice'])) else: print('Successful payment RECEIVED!!!') pprint(msg) print(SuccessfulPayment(**msg['successful_payment']))
async def on_chat_message(msg): content_type, chat_type, chat_id = amanobot.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 = ReplyKeyboardRemove() 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 on_chosen_inline_result(self, msg): from pprint import pprint pprint(msg) result_id, from_id, query_string = amanobot.glance( msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
def on_pre_checkout_query(msg): query_id, from_id, invoice_payload = amanobot.glance(msg, flavor='pre_checkout_query') print('Pre-Checkout query:') pprint(msg) bot.answerPreCheckoutQuery(query_id, True)
def see_every_content_types(msg): global expected_content_type, content_type_iterator flavor = amanobot.flavor(msg) if flavor == 'chat': content_type, chat_type, chat_id = amanobot.glance(msg) from_id = msg['from']['id'] if chat_id != USER_ID and from_id != USER_ID: print 'Unauthorized user:'******'Please give me a %s.' % expected_content_type) else: bot.sendMessage( chat_id, 'It is not a %s. Please give me a %s, please.' % (expected_content_type, expected_content_type)) except StopIteration: # reply to sender because I am kicked from group already bot.sendMessage(from_id, 'Thank you. I am done.') else: raise amanobot.BadFlavor(msg)
def handle(msg): content_type, chat_type, chat_id = amanobot.glance(msg) #print(msg) data = datetime.now(timezone('Brazil/East')).strftime('%Y%m%d') if content_type == 'text': if '/saude' in msg['text']: EnviaPergunta(chat_id, data) if '/resultado' in msg['text'] : CarregaResultado(chat_id) # bot.sendMessage(chat_id, "Escolha a data para o resultado:",reply_markup=keybResult) if 'reply_to_message' in msg: id_pergunta = msg['reply_to_message']['message_id'] from_pergunta = msg['reply_to_message']['from']['username'] user_id = msg['from']['id'] resposta = msg['text'] me = bot.getMe() if from_pergunta == me['username']: #é uma pergunta feita pelo bot? if isPerguntaValida(chat_id,id_pergunta): #grava a resposta insertResposta(user_id, chat_id,id_pergunta,data,resposta)
def on_inline_query(msg): def compute(): articles = [InlineQueryResultArticle( id='abc', title='HK', input_message_content=InputTextMessageContent(message_text='Hong Kong'), url='https://www.google.com', hide_url=True), {'type': 'article', 'id': 'def', 'title': 'SZ', 'input_message_content': {'message_text': 'Shenzhen'}, 'url': 'https://www.yahoo.com'}] photos = [InlineQueryResultPhoto( id='123', photo_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf', thumb_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'), {'type': 'photo', 'id': '345', 'photo_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'thumb_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'caption': 'Caption', 'title': 'Title', 'input_message_content': {'message_text': 'Shenzhen'}}] games = [InlineQueryResultGame( id='abc', game_short_name='sunchaser')] results = random.choice([articles, photos, games]) return results query_id, from_id, query = amanobot.glance(msg, flavor='inline_query') if from_id != USER_ID: print 'Unauthorized user:', from_id return examine(msg, InlineQuery) answerer.answer(msg, compute)
def compute(): query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query') print('Computing for: %s' % query_string) articles = [InlineQueryResultArticle( id='abcde', title='Telegram', input_message_content=InputTextMessageContent(message_text='Telegram is a messaging app')), dict(type='article', id='fghij', title='Google', input_message_content=dict(message_text='Google is a search engine'))] photo1_url = 'https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf' photo2_url = 'https://www.telegram.org/img/t_logo.png' photos = [InlineQueryResultPhoto( id='12345', photo_url=photo1_url, thumb_url=photo1_url), dict(type='photo', id='67890', photo_url=photo2_url, thumb_url=photo2_url)] result_type = query_string[-1:].lower() if result_type == 'a': return articles elif result_type == 'p': return photos else: results = articles if random.randint(0,1) else photos if result_type == 'b': return dict(results=results, switch_pm_text='Back to Bot', switch_pm_parameter='Optional_start_parameter') else: return dict(results=results)
def on_chat_message(msg): content_type, chat_type, chat_id = amanobot.glance(msg) keyboard = InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text='Press me', callback_data='press')], ]) bot.sendMessage(chat_id, 'Use inline keyboard', reply_markup=keyboard)
async def on_chat_message(self, msg): content_type, chat_type, chat_id = glance(msg) await self.sender.sendMessage( 'Press START to do some math ...', reply_markup=InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text='START', callback_data='start'), ]])) self.close() # let Quizzer take over
def compute_answer(): query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query') print(self.id, ':', 'Inline Query:', query_id, from_id, query_string) articles = [{'type': 'article', 'id': 'abc', 'title': query_string, 'message_text': query_string}] return articles
def on_chat_message(msg): content_type, chat_type, chat_id = amanobot.glance(msg) if content_type == 'successful_payment': print('Successful payment RECEIVED!!!') pprint(msg) else: print('Chat message:') pprint(msg)
def on_chat_message(self, msg): content_type, chat_type, chat_id = amanobot.glance(msg) if 'edit_date' not in msg: self.sendMessage(chat_id, 'Edit the message, please.') else: self.sendMessage(chat_id, 'Add me to a group, please.') r = amanobot.helper.Router(by_content_type(), make_content_type_routing_table(self)) self._router.routing_table['chat'] = r.route
async def on_pre_checkout_query(msg): query_id, from_id, invoice_payload, currency, total_amount = amanobot.glance( msg, flavor='pre_checkout_query', long=True) print('Pre-Checkout query:') print(query_id, from_id, invoice_payload, currency, total_amount) pprint(msg) print(PreCheckoutQuery(**msg)) await bot.answerPreCheckoutQuery(query_id, True)
def on_callback_query(msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') # print('Callback Query:', query_id, from_id, query_data) if query_data == 'press': # bot.answerCallbackQuery(query_id, text='Falei para não aperter o botão!') bot.sendMessage(from_id, 'Falei para não aperter o botão!') elif query_data == 'go': bot.sendMessage(-1001140402839, 'www.google.com') elif query_data == 'wiki': bot.sendMessage(-1001140402839, f"https://pt.wikipedia.org/wiki/")
def on_chosen_inline_result(msg): result_id, from_id, query = amanobot.glance(msg, flavor='chosen_inline_result') if from_id != USER_ID: print 'Unauthorized user:'******'Chosen inline query:' pprint.pprint(msg)
def on_callback_query(self, msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') if query_data == 'yes': self._cancel_last() self.sender.sendMessage('Thank you!') self.close() else: self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.') self._cancel_last() self._propose()
async def on_callback_query(self, msg): if 'inline_message_id' in msg: inline_message_id = msg['inline_message_id'] ballot = self._ballots[inline_message_id] query_id, from_id, query_data = glance(msg, flavor='callback_query') if from_id in ballot: await self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % ballot[from_id]) else: await self.bot.answerCallbackQuery(query_id, text='Ok') ballot[from_id] = query_data
def on_chat_message(self, msg): content_type, chat_type, chat_id = amanobot.glance(msg) if 'edit_date' not in msg: self.sendMessage(chat_id, 'Edit the message, please.') else: self.sendMessage(chat_id, 'Add me to a group, please.') # Make a router to route `new_chat_member` and `left_chat_member` r = amanobot.helper.Router(by_content_type(), make_content_type_routing_table(self)) # Replace current handler with that router self._router.routing_table['chat'] = r.route
def on_inline_query(msg): query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query') print('Inline Query:', query_id, from_id, query_string) articles = [ InlineQueryResultArticle(id='abc', title='ABC', input_message_content=InputTextMessageContent( message_text='Hello')) ] bot.answerInlineQuery(query_id, articles)
def on_chat_message(self, msg): content_type, chat_type, chat_id = amanobot.glance(msg) if chat_id in self._exclude: print('Chat id %d is excluded.' % chat_id) return if content_type != 'text': print('Content type %s is ignored.' % content_type) return print('Storing message: %s' % msg) self._store.put(msg)
def compute(): query_id, from_id, query_string = glance(msg, flavor='inline_query') print('Inline query:', query_id, from_id, query_string) weekdays = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ] query_string = query_string.lower() query_weekdays = [ day[0] for day in enumerate(weekdays) if day[1].startswith(query_string) ] def days_to(today, target): d = target - today if d <= 0: d += 7 return timedelta(days=d) today = datetime.today() deltas = [ days_to(today.weekday(), target) for target in query_weekdays ] def make_result(today, week_delta, day_delta): future = today + week_delta + day_delta n = 0 if future.weekday() > today.weekday() else 1 n += int(week_delta.days / 7) return InlineQueryResultArticle( id=future.strftime('%Y-%m-%d'), title=('next ' * n if n > 0 else 'this ') + weekdays[future.weekday()].capitalize(), input_message_content=InputTextMessageContent( message_text=future.strftime('%A, %Y-%m-%d')), reply_markup=InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text='Yes', callback_data='yes'), InlineKeyboardButton(text='No', callback_data='no'), ]])) results = [] for i in range(0, 3): weeks = timedelta(weeks=i) for d in deltas: results.append(make_result(today, weeks, d)) return results
def compute(): query_id, from_id, query_string = amanobot.glance( msg, flavor='inline_query') print('Inline Query:', query_id, from_id, query_string) articles = [ InlineQueryResultArticle( id='abc', title=query_string, input_message_content=InputTextMessageContent( message_text=query_string)) ] return articles
def on_inline_query(msg): query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query') print('Inline Query:', query_id, from_id, query_string) # Compose your own answers articles = [{ 'type': 'article', 'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning' }] bot.answerInlineQuery(query_id, articles)
def on_callback_query(msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') sos = emojis.encode(":sos:") CD = emojis.encode(":minidisc:") chat_id = msg['message']['chat']['id'] name = msg['message']['from']['first_name'] click = ''.join(query_data) click = click.split(' ') bot.answerCallbackQuery(query_id) sites = ['https://www.youtube.com/', 'https://www.mercadolivre.com.br/', 'https://open.spotify.com/', 'https://pagseguro.uol.com.br/', 'https://www.netflix.com/br/', 'http://www.superflix.net/', 'https://www.thingiverse.com/explore/newest/3d-printing', 'https://komoda-eletro-eletronica.webnode.com/', 'https://ifttt.com/discover', 'https://blynk.io/en/getting-started'] if click[0] == 'go': bot.sendMessage(chat_id, f"https://www.google.com/search?q={click[1]}") bot.sendMessage(chat_id, 'Esta satisfeito com a pesquisa?') elif click[0] == 'wiki': bot.sendMessage(chat_id, f"https://pt.wikipedia.org/wiki/{click[1]}") elif query_data == 'L': bot.sendMessage(chat_id, "https://t.me/joinchat/Fj1EnkP5Kpfzs8IrrfPz2Q") elif query_data == 'SOS': bot.sendMessage(chat_id, 'Para pesquisar digite, ( hall pesquisar + o que deseja pesquisar) e ' 'aperte o botão de sua escolha!') bot.sendMessage(chat_id, "Digite (hall1 + nome) para receber os usuarios novos \nDigite hall2 " "para alertar usuarios sobre foto de perfil") bot.sendMessage(chat_id, text=sos) elif query_data == 'url': for i in sites: bot.sendMessage(chat_id, text=i) sleep(1.50) bot.sendMessage(chat_id, 'Por enquanto eu só conheço esses sites!') elif query_data == 'co': bot.sendMessage(chat_id, 'Conteúdo:', reply_markup=botao4()) elif query_data == 'M': bot.sendMessage(chat_id, '***OPÇÕES DO MENU CLIQUE***', reply_markup=botao2()) elif query_data == 'ha': bot.sendMessage(chat_id, 'https://anos-80.mp3cielo.com/') bot.sendMessage(chat_id, CD) elif query_data == 'mu': for i in audio[0:51]: bot.sendAudio(from_id, audio=i) bot.sendMessage(from_id, 'Por enquanto só enviarei esses!') bot.sendMessage(chat_id, f"Enviei no seu privado {name}") elif query_data == 'curs': bot.sendMessage(chat_id, f"Sem cursos no momento!") elif query_data == 'li': bot.sendMessage(chat_id, 'Ainda não tenho livros adicionados aqui!')
def on_chat_message(self, msg): content_type, chat_type, chat_id = amanobot.glance(msg) if content_type != 'text': print('Not a text message.') return if msg['text'] != '/vote': print('Not /vote') return if self._ballot_box is not None: self.sender.sendMessage('Voting still in progress') else: self._init_ballot()
def on_callback_query(msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') sos = emojis.encode(":sos:") CD = emojis.encode(":minidisc:") chat_id = msg['message']['chat']['id'] click = ''.join(query_data) click = click.split(' ') bot.answerCallbackQuery(query_id) sites = ['https://www.youtube.com/', 'https://www.mercadolivre.com.br/', 'https://open.spotify.com/', 'https://komoda-eletro-eletronica.webnode.com/'] if click[0] == 'go': bot.sendMessage(chat_id, f"https://www.google.com/search?q={click[1]}") bot.sendMessage(chat_id, 'Esta satisfeito com a pesquisa?') elif click[0] == 'wiki': bot.sendMessage(chat_id, f"https://pt.wikipedia.org/wiki/{click[1]}") elif query_data == 'L': bot.sendMessage(chat_id, "https://t.me/joinchat/Fj1EnkP5Kpfzs8IrrfPz2Q") elif query_data == 'SOS': bot.sendMessage(chat_id, 'Para pesquisar digite, ( hall pesquisar + o que deseja pesquisar) e ' 'aperte o botão de sua escolha!') bot.sendMessage(chat_id, "Digite (hall1 + nome) para receber os usuarios novos \nDigite hall2 " "para alertar usuarios sobre foto de perfil") bot.sendMessage(chat_id, text=sos) elif query_data == 'url': for i in sites: bot.sendMessage(chat_id, text=i) sleep(1.50) bot.sendMessage(chat_id, 'Esses são os sites mais usados!') elif query_data == 'co': bot.sendMessage(chat_id, 'Conteúdo:', reply_markup=botao4()) elif query_data == 'M': bot.sendMessage(chat_id, '***OPÇÕES DO MENU CLIQUE***', reply_markup=botao2()) elif query_data == 'ha': bot.sendMessage(chat_id, 'https://anos-80.mp3cielo.com/') bot.sendMessage(chat_id, CD) elif query_data == 'mu': audio = abre_id('ID_music.txt') for i in audio[0:15]: bot.sendAudio(from_id, audio=i) bot.sendMessage(from_id, 'Por enquanto só enviarei esses!') bot.sendMessage(chat_id, f"Enviei no seu privado") elif query_data == 'curs': bot.sendMessage(chat_id, f"Sem cursos no momento! Procure nos arquivos do grupo que tem varios tutoriais") elif query_data == 'li': bot.sendMessage(chat_id, f"Sem HQs no momento!")
async def on_callback_query(msg): query_id, from_id, data = amanobot.glance(msg, flavor='callback_query') print('Callback query:', query_id, from_id, data) if data == 'notification': await bot.answerCallbackQuery(query_id, text='Notification at top of screen') elif data == 'alert': await bot.answerCallbackQuery(query_id, text='Alert!', show_alert=True) elif data == 'edit': global message_with_inline_keyboard if message_with_inline_keyboard: msg_idf = amanobot.message_identifier(message_with_inline_keyboard) await bot.editMessageText(msg_idf, 'NEW MESSAGE HERE!!!!!') else: await bot.answerCallbackQuery(query_id, text='No previous message to edit')