示例#1
0
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)
示例#2
0
文件: bot.py 项目: gsilos/telegrambot
def botao4():
    conte = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Cursos', callback_data='curs'),
         InlineKeyboardButton(text='Livros', callback_data='li')],
        [InlineKeyboardButton(text='Musicas', callback_data='mu')],
        [InlineKeyboardButton(text='Radios', callback_data='ha')],
    ])
    return conte
示例#3
0
文件: bot.py 项目: gsilos/telegrambot
def botao2():
    menu = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Link do grupo', callback_data='L'),
         InlineKeyboardButton(text='Help', callback_data='SOS')],
        [InlineKeyboardButton(text='Sites + usados', callback_data='url')],
        [InlineKeyboardButton(text='Conteúdo', callback_data='co')],
    ])
    return menu
示例#4
0
class Lover(amanobot.helper.ChatHandler):
    keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                   InlineKeyboardButton(text='Yes', callback_data='yes'),
                   InlineKeyboardButton(text='um ...', callback_data='no'),
               ]])

    def __init__(self, *args, **kwargs):
        super(Lover, self).__init__(*args, **kwargs)

        # Retrieve from database
        global propose_records
        if self.id in propose_records:
            self._count, self._edit_msg_ident = propose_records[self.id]
            self._editor = amanobot.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._count = 0
            self._edit_msg_ident = None
            self._editor = None

    def _propose(self):
        self._count += 1
        sent = self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self.keyboard)
        self._editor = amanobot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = amanobot.message_identifier(sent)

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        self._propose()

    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()

    def on__idle(self, event):
        self.sender.sendMessage('I know you may need a little time. I will always be here for you.')
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._count, self._edit_msg_ident)
示例#5
0
            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'),
                    ]]))
示例#6
0
文件: quiza.py 项目: n8wachT/amanobot
 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
示例#7
0
    def _init_ballot(self):
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
            InlineKeyboardButton(text='Yes', callback_data='yes'),
            InlineKeyboardButton(text='Nah!!!!', callback_data='no'),
        ]])
        sent = self.sender.sendMessage("Let's Vote ...", reply_markup=keyboard)

        self._ballot_box = {}
        self._keyboard_msg_ident = amanobot.message_identifier(sent)
        self._editor = amanobot.helper.Editor(self.bot,
                                              self._keyboard_msg_ident)

        # Generate an expiry event 30 seconds later
        self._expired_event = self.scheduler.event_later(
            30, ('_vote_expired', {
                'seconds': 30
            }))
示例#8
0
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)
示例#9
0
    async def _init_ballot(self):
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
            InlineKeyboardButton(text='Yes', callback_data='yes'),
            InlineKeyboardButton(text='Nah!!!!', callback_data='no'),
        ]])
        sent = await self.sender.sendMessage("Let's Vote ...",
                                             reply_markup=keyboard)

        self._member_count = await self.administrator.getChatMembersCount(
        ) - 1  # exclude myself, the bot

        self._ballot_box = {}
        self._keyboard_msg_ident = message_identifier(sent)
        self._editor = amanobot.aio.helper.Editor(self.bot,
                                                  self._keyboard_msg_ident)

        # Generate an expiry event 30 seconds later
        self._expired_event = self.scheduler.event_later(
            30, ('_vote_expired', {
                'seconds': 30
            }))
示例#10
0
def EnviaPerguntas(chat_id):
	data = datetime.now(timezone('Brazil/East')).strftime('%Y%m%d')

	keybVoto = InlineKeyboardMarkup(inline_keyboard=[[
			InlineKeyboardButton(text="Sim", callback_data=data+'|sim'),
			InlineKeyboardButton(text="Não", callback_data=data+'|nao'),
	]])

	stamps = getTimes(chat_id)
	send_question = True if (len(stamps) == 0) else True if (str(data) not in stamps[0]) else False
	if (send_question):
		enviada = bot.sendMessage(chat_id,"Você dormiu mais de 6 horas por noite a cada dia nessa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
		enviada = bot.sendMessage(chat_id,"Você praticou alguma atividade física em ao menos 1 dia essa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
		enviada = bot.sendMessage(chat_id,"Você fez algo que te dá muito prazer, fora trabalho, em ao menos um dia essa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
		enviada = bot.sendMessage(chat_id,"Você teve algum momento de autocuidado (relacionado à auto estima, beleza etc) em ao menos um dia essa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
	else:
		bot.sendMessage(chat_id,"Já foi enviada uma enquete hoje")
示例#11
0
def callback(msg):
	query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query')
	#print(msg)
	message_id = msg['message']['message_id']
	chat_id = msg['message']['chat']['id']

	refreshButton = False
	data = query_data.split('|')
	timestamp = data[0]

	if data[1] == 'sim' or data[1] == 'nao':
		if data[1] == 'sim':
			if count('sim',from_id, chat_id,message_id) == 0:
				delete('nao',from_id, chat_id,message_id,timestamp)
				insert('sim',from_id, chat_id,message_id,timestamp)
				bot.answerCallbackQuery(query_id,"Votado!")
				refreshButton = True
			else:
				bot.answerCallbackQuery(query_id,"Você já votou nessa opção!")

		if data[1] == 'nao':
			if count('nao',from_id, chat_id,message_id) == 0:
				delete('sim',from_id, chat_id,message_id,timestamp)
				insert('nao',from_id, chat_id,message_id,timestamp)
				bot.answerCallbackQuery(query_id,"Votado!")
				refreshButton = True
			else:
				bot.answerCallbackQuery(query_id,"Você já votou nessa opção!")
		
		count_sim = count('sim',None, chat_id,message_id)
		count_nao = count('nao',None, chat_id,message_id)

		keybVoto = InlineKeyboardMarkup(inline_keyboard=[[
						InlineKeyboardButton(text='Sim' +' '+ str(count_sim), callback_data=timestamp+'|sim'),
						InlineKeyboardButton(text='Não' + ' ' + str(count_nao), callback_data=timestamp+'|nao'),
		]])
		ident_mensagem = (chat_id,message_id)
		if(refreshButton):
			bot.editMessageReplyMarkup(ident_mensagem, reply_markup=keybVoto)
示例#12
0
文件: quiz.py 项目: n8wachT/amanobot
    def _show_next_question(self):
        x = random.randint(1,50)
        y = random.randint(1,50)
        sign, op = random.choice([('+', lambda a,b: a+b),
                                  ('-', lambda a,b: a-b),
                                  ('x', lambda a,b: a*b)])
        answer = op(x,y)
        question = '%d %s %d = ?' % (x, sign, y)
        choices = sorted(list(map(random.randint, [-49]*4, [2500]*4)) + [answer])

        self.editor.editMessageText(question,
            reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[
                    list(map(lambda c: InlineKeyboardButton(text=str(c), callback_data=str(c)), choices))
                ]
            )
        )
        return answer
示例#13
0
async def rextester(msg):
    if msg.get('text'):
        if msg['text'].startswith('/rextester'):
            text = msg['text'][10:]
            rex = re.split('[ |\n]+', text, 2)
            code = rex[2:]
            reply_id = msg['message_id']
            if not text:
                await bot.sendMessage(
                    msg['chat']['id'],
                    """💻Bem vindo ao meu interpretador de codigos, digite meu comando seguido de uma linguagem de programação seguido de seu codigo, ex: /rextester python seu_codigo!
                    
 💻Linguagens Suportadas: -ada -bash -brainfuck -c_clang -c_gcc -c_vc -c# -c++_clang -c++_gcc -c++_vc++ -d -elixir -erlang -f#  -fortran -go -haskell -java -javascript -kotlin -lisp -lua -mysql -nasm -node.js -objective-c -ocaml -octave -oracle -pascal -perl -php -postgresql -prolog -python -python2 -python3 -py3 -py2 -r -ruby  -scala -scheme -sql server -swift -tcl -vb.net """,
                    reply_to_message_id=reply_id)
            elif len(code) == 0:
                await bot.sendMessage(
                    msg['chat']['id'],
                    '💻me de uma linguagem ex /rextester python seu_codigo',
                    reply_to_message_id=reply_id)
            elif msg['text'].split()[1] not in languages:
                await bot.sendMessage(msg['chat']['id'],
                                      '💻linguagem errada.',
                                      reply_to_message_id=reply_id)
            else:
                langs = rex[1]
                program = ' '.join(code).strip()
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                elif warning:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                elif result and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n*Errors:*\n`{errors}`"
                elif errors:
                    resp = f"*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                else:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                if len(resp) > 4096:
                    await bot.sendMessage(msg['chat']['id'],
                                          'muito longo!',
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
                else:
                    await bot.sendMessage(msg['chat']['id'],
                                          resp,
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
            return True

    elif msg.get('query'):
        if msg['query'].split()[0].lower() == 'run' and len(
                msg['query'].split()) >= 2:
            rex = re.split('[ |\n]+', msg['query'], 2)
            if len(rex) == 2:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='give me code',
                        input_message_content=InputTextMessageContent(
                            message_text='give me code'))
                ]
            elif rex[1].lower() not in languages:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='unknown Lang',
                        input_message_content=InputTextMessageContent(
                            message_text='unknown lang'))
                ]
            else:
                langs = rex[1]
                program = rex[2]
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                elif warning:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                    desc = result or 'NULL'
                elif result and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Errors:*\n`{errors}`"
                    desc = result or 'NULL'
                elif errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                else:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                    desc = result or 'NULL'
                print(shorten_stats(stats))
                print(len(shorten_stats(stats)))
                print(stats)
                print(len(stats))
                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text='Stats',
                                             callback_data='rstats ' +
                                             shorten_stats(stats))
                    ],
                ])
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title=langs,
                        description=desc,
                        input_message_content=InputTextMessageContent(
                            message_text=resp, parse_mode='markdown'),
                        reply_markup=keyboard)
                ]

            return await bot.answerInlineQuery(msg['id'],
                                               results=articles,
                                               cache_time=60,
                                               is_personal=True)

    elif msg.get('data'):
        if msg['data'].startswith('rstats '):
            await bot.answerCallbackQuery(msg['id'],
                                          unshorten_stats(msg['data'][7:]),
                                          show_alert=True)
示例#14
0
文件: bot.py 项目: gsilos/telegrambot
def botao3():
    redi = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Menu', callback_data='M')],
    ])
    return redi
示例#15
0
文件: bot.py 项目: gsilos/telegrambot
def botao1(tt=None):
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Google', callback_data=f'go {tt}'),
         InlineKeyboardButton(text='Wikipédia', callback_data=f'wiki {tt}')],
    ])
    return keyboard
示例#16
0
async def rextester(msg):
    if msg.get('text'):
        if msg['text'].startswith('/rextester') or msg['text'].startswith(
                '!rextester'):
            text = msg['text'][10:]
            rex = re.split('[ |\n]+', text, 2)
            code = rex[2:]
            reply_id = msg['message_id']
            if not text:
                await bot.sendMessage(msg['chat']['id'],
                                      'give me lang',
                                      reply_to_message_id=reply_id)
            elif len(code) == 0:
                await bot.sendMessage(msg['chat']['id'],
                                      'give me code',
                                      reply_to_message_id=reply_id)
            elif msg['text'].split()[1] not in languages:
                await bot.sendMessage(msg['chat']['id'],
                                      'wrong langs',
                                      reply_to_message_id=reply_id)
            else:
                langs = rex[1]
                program = ' '.join(code).strip()
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                elif warning:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                elif result and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n*Errors:*\n`{errors}`"
                elif errors:
                    resp = f"*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                else:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                if len(resp) > 4096:
                    await bot.sendMessage(msg['chat']['id'],
                                          'msgs are too long!',
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
                else:
                    await bot.sendMessage(msg['chat']['id'],
                                          resp,
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
            return True

    elif msg.get('query'):
        if msg['query'].split()[0].lower() == 'run' and len(
                msg['query'].split()) >= 2:
            rex = re.split('[ |\n]+', msg['query'], 2)
            if len(rex) == 2:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='give me code',
                        input_message_content=InputTextMessageContent(
                            message_text='give me code'))
                ]
            elif rex[1].lower() not in languages:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='unknown Lang',
                        input_message_content=InputTextMessageContent(
                            message_text='unknown lang'))
                ]
            else:
                langs = rex[1]
                program = rex[2]
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                elif warning:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                    desc = result or 'NULL'
                elif result and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Errors:*\n`{errors}`"
                    desc = result or 'NULL'
                elif errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                else:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                    desc = result or 'NULL'
                print(shorten_stats(stats))
                print(len(shorten_stats(stats)))
                print(stats)
                print(len(stats))
                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text='Stats',
                                             callback_data='rstats ' +
                                             shorten_stats(stats))
                    ],
                ])
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title=langs,
                        description=desc,
                        input_message_content=InputTextMessageContent(
                            message_text=resp, parse_mode='markdown'),
                        reply_markup=keyboard)
                ]

            return await bot.answerInlineQuery(msg['id'],
                                               results=articles,
                                               cache_time=60,
                                               is_personal=True)

    elif msg.get('data'):
        if msg['data'].startswith('rstats '):
            await bot.answerCallbackQuery(msg['id'],
                                          unshorten_stats(msg['data'][7:]),
                                          show_alert=True)