async def do_welcomesecurity(event, strings, from_id, chat_id): welcome_security = mongodb.welcome_security.find_one({'chat_id': chat_id}) if welcome_security and welcome_security['security'] == 'soft': buttons = [[ Button.inline(strings['clik2tlk_btn'], 'wlcm_{}_{}'.format(from_id, chat_id)) ]] time_val = int(time.time() + 60 * 60) # Mute 1 hour try: await mute_user(event, int(from_id), chat_id, time_val) except Exception as err: await event.reply(err) text = strings['wlcm_sec'].format(mention=await user_link(from_id)) await event.reply(text, buttons=buttons) elif welcome_security and welcome_security['security'] == 'hard': buttons = [[ Button.inline(strings['clik2tlk_btn'], 'wlcm_{}_{}'.format(from_id, chat_id)) ]] try: await mute_user(event, int(from_id), chat_id, None) except Exception as err: await event.reply(err) text = strings['wlcm_sec'].format(mention=await user_link(from_id)) await event.reply(text, buttons=buttons)
def button_parser(chat_id, texts, pm=False, aio=False, row_width=None): buttons = InlineKeyboardMarkup(row_width=row_width) if aio else [] pattern = r'\[(.+?)\]\((button|btn)(.+?)(:.+?|)(:same|)\)(\n|)' raw_buttons = re.findall(pattern, texts) text = re.sub(pattern, '', texts) for raw_button in raw_buttons: name = raw_button[0] action = raw_button[2] argument = raw_button[3][1:].lower() if raw_button[3] else '' if action in BUTTONS: cb = BUTTONS[action] string = f'{cb}_{argument}_{chat_id}' if argument else f'{cb}_{chat_id}' if aio: start_btn = InlineKeyboardButton( name, url=f'https://t.me/{BOT_USERNAME}?start=' + string) cb_btn = InlineKeyboardButton(name, callback_data=string) else: start_btn = Button.url( name, f'https://t.me/{BOT_USERNAME}?start=' + string) cb_btn = Button.inline(name, string) if cb.endswith('sm'): btn = cb_btn if pm else start_btn elif cb.endswith('cb'): btn = cb_btn elif cb.endswith('start'): btn = start_btn elif cb.startswith('url'): btn = Button.url(name, argument) elif action == 'url': if argument[0] == '/' and argument[1] == '/': argument = argument[2:] btn = InlineKeyboardButton( name, url=argument) if aio else Button.url(name, argument) else: # If btn not registred btn = None if argument: text += f'\n[{name}].(btn{action}:{argument})' else: text += f'\n[{name}].(btn{action})' continue if aio: buttons.insert(btn) if raw_button[4] else buttons.add(btn) else: if len(buttons) < 1 and raw_button[4]: buttons.add(btn) if aio else buttons.append([btn]) else: buttons[-1].append(btn) if raw_button[4] else buttons.append( [btn]) if not aio and len(buttons) == 0: buttons = None if not text or text == ' ': # TODO: Sometimes we can return text == ' ' text = None return text, buttons
def button_parser(chat_id, texts): buttons = [] raw_buttons = re.findall(r'\[(.+?)\]\(button(.+?):(.+?)(:same|)\)', texts) text = re.sub(r'\[(.+?)\]\(button(.+?):(.+?)(:same|)\)', '', texts) for raw_button in raw_buttons: if raw_button[1] == 'url': url = raw_button[2] if url[0] == '/' and url[0] == '/': url = url[2:] t = [custom.Button.url(raw_button[0], url)] elif raw_button[1] == 'note': t = [ Button.inline(raw_button[0], 'get_note_{}_{}'.format(chat_id, raw_button[2])) ] elif raw_button[1] == 'alert': t = [ Button.inline(raw_button[0], 'get_alert_{}_{}'.format(chat_id, raw_button[2])) ] elif raw_button[1] == 'deletemsg': t = [ Button.inline( raw_button[0], 'get_delete_msg_{}_{}'.format(chat_id, raw_button[2])) ] if raw_button[3]: new = buttons[-1] + t buttons = buttons[:-1] buttons.append(new) else: buttons.append(t) return text, buttons
async def on_click_game(self, event: events.CallbackQuery.Event): mes = await event.get_message() logger.info( f'{get_member(event.sender_id)} clicked game button (mes_id={mes.id}, chat_id={event.chat_id})' ) lvl, cur, sel = [int(x) for x in event.pattern_match.groups()] buttons = (await mes.get_buttons())[0] # first row complexity = 4 * len(buttons)**3 chance = lvl / (lvl + complexity) if sel != cur and random.random() < chance: buttons[cur] = Button.inline(self.empty_ch) buttons[sel] = Button.inline(self.dead_ch) await mes.edit('🎉 Победа! 🎉', buttons=buttons) await asyncio.sleep(1) await mes.edit( buttons=Button.inline("Получить награду", self.game_butt_id + 'f')) else: new_cur = random.randrange(len(buttons) - 1) if new_cur >= cur: new_cur = new_cur + 1 lvl += 1 game_state = self.game_butt_id + str(lvl) + ' ' + str(new_cur) buttons = [ Button.inline(self.empty_ch if i != new_cur else self.alive_ch, game_state + ' ' + str(i)) for i in range(len(buttons)) ] await mes.edit(buttons=buttons) raise events.StopPropagation
async def _locked_start_poll( event: Union[events.NewMessage.Event, Message]) -> None: global current_vote if current_vote: await event.reply('There\'s already an ongoing sticker poll.') return elif last_accepted + ADD_COOLDOWN > int(time()): await event.reply('Less than 24 hours have passed since the ' 'previous sticker was added.') return emoji = event.pattern_match.group(1) try: _, sender_name = WEIGHTS[event.sender_id] except KeyError: await event.reply('Please upgrade to a Telethon OffTopic Premium ' 'Membership to start sticker polls.') return orig_evt: Message = await event.get_reply_message() # TODO add support for animated stickers if not orig_evt.photo and (not orig_evt.sticker or orig_evt.sticker.mime_type == 'application/x-tgsticker'): return filename = Path(DATA_FILE_FORMAT.format(ts=int(time()))) await orig_evt.download_media(filename) delete_task = asyncio.ensure_future(event.delete(), loop=bot.loop) current_vote_status.clear() current_vote = { 'chat': event.chat_id, 'started_at': int(time()), 'sender_id': event.sender_id, 'sender_name': sender_name, 'score': 0, 'emoji': emoji, 'votes': {}, 'filepath': str(filename), 'animated': orig_evt.sticker and orig_evt.sticker.mime_type == 'application/x-tgsticker' } reply_evt: Message = await orig_evt.reply( POLL_TEMPLATE.format_map(get_template_data()), buttons=[Button.inline(UP, UP_DAT), Button.inline(DOWN, DOWN_DAT)], parse_mode='html') pin_task = asyncio.ensure_future(reply_evt.pin(), loop=bot.loop) current_vote['poll'] = reply_evt.id asyncio.ensure_future(wait_for_poll(), loop=bot.loop) await asyncio.gather(delete_task, pin_task, loop=bot.loop)
async def connect(event): user_id = event.from_id if not event.chat_id == user_id: return history = mongodb.connections.find_one({'user_id': user_id}) if not history: await event.reply( get_string("connections", "history_empty", event.chat_id)) return buttons = [] chat_title = mongodb.chat_list.find_one({'chat_id': history['btn1']}) buttons += [[ Button.inline("{}".format(chat_title['chat_title']), 'connect_{}'.format(history['btn1'])) ]] if history['btn2']: chat_title = mongodb.chat_list.find_one({'chat_id': history['btn2']}) buttons += [[ Button.inline("{}".format(chat_title['chat_title']), 'connect_{}'.format(history['btn2'])) ]] if history['btn3']: chat_title = mongodb.chat_list.find_one({'chat_id': history['btn3']}) buttons += [[ Button.inline("{}".format(chat_title['chat_title']), 'connect_{}'.format(history['btn3'])) ]] chat_title = mongodb.chat_list.find_one( {'chat_id': int(history['chat_id'])}) text = get_string("connections", "connected_chat", event.chat_id) text += chat_title['chat_title'] text += get_string("connections", "select_chat_to_connect", event.chat_id) await event.reply(text, buttons=buttons)
async def get_mod_help_callback(event): chat_id = event.chat_id module = re.search('mod_help_(.*)', str(event.data)).group(1)[:-1] text = get_string(module, "title", chat_id, dir="HELPS") text += '\n' lang = get_chat_lang(chat_id) buttons = [] for string in get_string(module, "text", chat_id, dir="HELPS"): if "HELPS" in LANGUAGES[lang]: text += LANGUAGES[lang]["HELPS"][module]['text'][string] else: text += LANGUAGES["en"]["HELPS"][module]['text'][string] text += '\n' if 'buttons' in LANGUAGES[lang]["HELPS"][module]: counter = 0 for btn in LANGUAGES[lang]["HELPS"][module]['buttons']: counter += 1 btn_name = LANGUAGES[lang]["HELPS"][module]['buttons'][btn] t = [Button.inline(btn_name, btn)] if counter % 2 == 0: new = buttons[-1] + t buttons = buttons[:-1] buttons.append(new) else: buttons.append(t) buttons += [[Button.inline("Back", 'get_help')]] await event.edit(text, buttons=buttons)
async def img(event): j = await event.client(GetFullUserRequest(event.chat_id)) mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.from_id})\nMesaj: {event.message.message}" await bot.send_message("By_Azade", mesaj) markup = bot.build_reply_markup([ Button.url(text='📍 Kanal Linkleri', url="t.me/KanalLinkleri"), Button.url(text='👤 Yapımcı', url="t.me/By_Azade") ]) url = event.pattern_match.group(1) if url: x = await event.reply("`İşlem yapılıyor lütfen bekleyiniz...`") get_url = get_download_url(url) j = download_image(get_url) if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY): os.makedirs(TMP_DOWNLOAD_DIRECTORY) c_time = time.time() await event.client.send_file( event.chat_id, j, caption="**Daha fazlası için**\n\n@KanalLinkleri", force_document=False, allow_cache=False, reply_to=event.message.id, buttons=markup, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, event, c_time, "yükleniyor..."))) await event.delete() await x.delete() os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg') else: await event.reply("**bana komutla beraber link gönder.**")
async def img(event): markup = bot.build_reply_markup([ Button.url(text='📍 My Channel', url="t.me/KanalLinkleri"), Button.url(text='👤 Developer', url="t.me/By_Azade") ]) x = await event.reply("`Progressing...`") url = event.pattern_match.group(1) get_url = get_download_url(url) j = download_image(get_url) if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY): os.makedirs(TMP_DOWNLOAD_DIRECTORY) c_time = time.time() await event.client.send_file( event.chat_id, j, caption="`For more` @KanalLinkleri", force_document=False, allow_cache=False, reply_to=event.message.id, buttons=markup, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, event, c_time, "trying to upload"))) await event.delete() await x.delete() os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg')
async def vid(event): j = await event.client(GetFullUserRequest(event.chat_id)) mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.from_id})\nMesaj: {event.message.message}" await bot.send_message("By_Azade", mesaj) markup = bot.build_reply_markup([ Button.url(text='📍 Kanal Linkleri', url="t.me/KanalLinkleri"), Button.url(text='👤 Yapımcı', url="t.me/By_Azade") ]) url = event.pattern_match.group(1) if url: x = await event.reply("`işlem yapılıyor bekleyiniz...`") get_url = get_download_url(url) j = download_video(get_url) thumb_image_path = TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg" if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY): os.makedirs(TMP_DOWNLOAD_DIRECTORY) metadata = extractMetadata(createParser(j)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds width = 0 height = 0 thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = await take_screen_shot(j, os.path.dirname(os.path.abspath(j)), (duration / 2)) c_time = time.time() await event.client.send_file( event.chat_id, j, thumb=thumb, caption="**Daha fazlası için**\n\n@KanalLinkleri", force_document=False, allow_cache=False, reply_to=event.message.id, buttons=markup, attributes=[ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, event, c_time, "yükleniyor..."))) await event.delete() await x.delete() os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4') os.remove(thumb_image_path) else: await event.reply("**bana komutla beraber link gönder.**")
def get_showmore_buttons(search: str, start: int, total: int): """start: begin with 0 """ digest = hashlib.md5(search.encode()).hexdigest() previous_start = max((start - constants.MessagesEachSearch), 0) next_start = min((start + constants.MessagesEachSearch), total) # print(previous_start, next_start) fsm = constants.CQ.FindShowMore button_left = Button.inline('⇦', data=fsm.format(digest=digest, start=previous_start)) button_right = Button.inline('⇨', data=fsm.format(digest=digest, start=next_start)) button_shown = Button.inline( f'{start + constants.MessagesEachSearch} / {total}') # MessagesEachSearch/total ⇨ if start == 0: return [button_shown, button_right] # ⇦ total/total if start + constants.MessagesEachSearch >= total: button_shown = Button.inline(f'{total} / {total}') return [button_left, button_shown] # ⇦ start+MessagesEachSearch/total ⇨ return [button_left, button_shown, button_right]
async def callquery(event): data = event.data.decode("utf-8") if data.startswith("nodelete"): filename = data.split("nodelete-")[1] await Yandex.publish(filename) file = await Yandex.get_meta(filename) await event.edit( f"**Here is the link of the old file: ** [Link]({file.public_url})", buttons=Button.url('🔗 Public Link', file.public_url)) elif data.startswith("remove"): filename = data.split("remove-")[1] await event.edit( f"**Are you sure for delete `{filename}` permanently?**", buttons=[ Button.inline('✅ Yes', f"yes-{filename}"), Button.inline('❌ No', "no") ]) elif data.startswith("yes"): filename = data.split("yes-")[1] await Yandex.remove(filename, permanently=True) return await event.edit(f"✅ **Deleted successfully!**") elif data == "no": return await event.edit("__OK! File will not be deleted.__") elif data.startswith("publish"): filename = data.split("publish-")[1] await Yandex.publish(filename) file = await Yandex.get_meta(filename) await event.edit( f"__✅ I made the file public.__ **Here is public link: ** [Link]({file.public_url})", buttons=Button.url('🔗 Public Link', file.public_url)) return remove(file) elif data == "nopublish": return await event.edit("__OK! Only you will access the file.__")
def help(cls, **kwargs): return ("useable commands and arguments are", [ [ Button.inline('Workpackages', data=b'workpackages'), Button.inline('Start') ], ])
async def handleAddChannel(event): await event.delete() async with bot.conversation(event.query.peer) as conv: btns = [Button.inline(text='Cancel', data=b'mainpage')] q = await conv.send_message('Enter channel link.', buttons=btns) try: resp = await conv.get_response() except asyncio.TimeoutError: await q.delete() conv.send_message('Timeout\nPlease try again...') conv.cancel() return channelLink = resp.message await resp.delete() await q.delete() valid, entity = await getEntity(channelLink) if valid: newChannel = { 'id': entity.id, 'title': entity.title, 'link': channelLink } await addChannel(newChannel) btns = [ Button.inline(text='Back', data=b'mainpage') ] await conv.send_message('Channel added to the list of channels.', buttons=btns) else: btns = [Button.inline(text='Back', data=b'mainpage')] await conv.send_message('The entered link is not a valid telegram channel link.', buttons=btns)
def commit(cls, **kwargs): # Stop # Note # Request Review print("HEYDIHOE") event = kwargs['event'] print(event) data = event.query.data.decode("utf-8").lower() pid = data.split(":")[1] from .models import Workpackage workpackage = Workpackage.objects.get(pid=pid) return ( f'`{workpackage.name}`', [ [ Button.inline( 'Stop', data=(f"wp_commit_handler:{pid}:waiting").encode()), #Button.inline('Note', data=(f"wp_note:{pid}").encode()) ], [ Button.inline( 'Request Review', data=(f"wp_commit_handler:{pid}:review").encode()) ], [Button.inline('Back')] ])
async def upload(event): if event.media is None: return mesaj = await event.reply("`Your file downloading! Please Wait...`") baslangic = time.time() filename = await event.download_media( progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, mesaj, baslangic, "Trying to Download Your File"))) await mesaj.edit("`Uploading to YaDisk! Please Wait...`") try: await Yandex.upload(filename, filename) except exceptions.PathExistsError: await mesaj.edit( "**You have already uploaded a file with this name.**\n__Do you want remove old file?__", buttons=[ Button.inline('✅ Yes', f'remove-{filename}'), Button.inline('❌ No', f'nodelete-{filename}') ]) except exceptions.UnauthorizedError: await mesaj.edit( "You are not logged to Yandex. Please use /login then try upload file." ) except Exception as e: print(str(e)) await mesaj.edit( "**✅ File has been successfully uploaded to Yandex. Do you want to make it public?**", buttons=[ Button.inline('✅ Yes', f'publish-{filename}'), Button.inline('❌ No', f'nopublish') ])
async def upload_url(event): filename = event.pattern_match.group(1) url = event.pattern_match.group(2) if url is None or filename is None: return await event.edit( "**You must provide url & filename!**\nExample: `/upload test.gif https://www.gmail.com/mail/help/images/logonew.gif`" ) event = await event.reply("`Your URL downloading! Please Wait...`") await download_file(url, filename, event, time.time(), event.client) await event.edit("`Uploading to YaDisk! Please Wait...`") try: await Yandex.upload(filename, filename) except exceptions.PathExistsError: await event.edit( "**You have already uploaded a file with this name.**\n__Do you want remove old file?__", buttons=[ Button.inline('✅ Yes', f'remove-{filename}'), Button.inline('❌ No', f'nodelete-{filename}') ]) except exceptions.UnauthorizedError: await event.edit( "You are not logged to Yandex. Please use /login then try upload file." ) except Exception as e: print(str(e)) await event.edit( "**✅ File has been successfully uploaded to Yandex. Do you want to make it public?**", buttons=[ Button.inline('✅ Yes', f'publish-{filename}'), Button.inline('❌ No', f'nopublish') ])
async def inline_handler(event): builder = event.builder input_str = event.pattern_match.group(1) plug = [*PLUGINS] plugs = [] if input_str == "all": for i in plug: try: plugs.append( await event.builder.document( f"./plugins/{i}.py", title=f"{i}.py", description=f"Module Found", text=f"{i}.py use .paste to paste in neko and raw..", buttons=[ [ Button.switch_inline( "Search Again..?", query="send all", same_peer=True ) ] ], ) ) except BaseException: pass await event.answer(plugs) else: try: ultroid = builder.document( f"./plugins/{input_str}.py", title=f"{input_str}.py", description=f"Module {input_str} Found", text=f"{input_str}.py use .paste to paste in neko and raw..", buttons=[ [ Button.switch_inline( "Search Again..?", query="send ", same_peer=True ) ] ], ) await event.answer([ultroid]) return except BaseException: ultroidcode = builder.article( title=f"Module {input_str}.py Not Found", description=f"No Such Module", text=f"No Module Named {input_str}.py", buttons=[ [ Button.switch_inline( "Search Again", query="send ", same_peer=True ) ] ], ) await event.answer([ultroidcode]) return
async def handler(event): try: me = await client.get_me() if not event.query.user_id == me.id: return await event.answer( "Sorry, You dont have permission to Access me!", alert=True) et = event.data.decode("UTF-8") if et == "back": sad = sad2 = sad3 = sad4 = None lol = 0 tbu = [[ Button.inline('❌ Close menu', b'close'), ]] for i in CMD_HELP: if lol == 0: sad = str(i) lol = 1 elif lol == 1: sad2 = str(i) lol = 2 elif lol == 2: sad3 = str(i) lol = 3 elif lol == 3: sad4 = str(i) lol = 0 if sad and sad2 and sad3 and sad4: tbu += [[ Button.inline(f"{sad}", f"{sad}"), Button.inline(f"{sad2}", f"{sad2}"), Button.inline(f"{sad3}", f"{sad3}"), Button.inline(f"{sad4}", f"{sad4}") ]] sad = sad2 = sad3 = sad4 = None if sad: tbu += [[Button.inline(f"{sad}", f"{sad}")]] if sad2: tbu += [[Button.inline(f"{sad2}", f"{sad2}")]] if sad3: tbu += [[Button.inline(f"{sad3}", f"{sad3}")]] return await event.edit( "For Support, Report bugs & help @errorsender_bot", buttons=tbu, link_preview=False) if et == "close": return await event.edit(" Help Menu Closed") if et in CMD_HELP: fci = [[ Button.inline('Go back', 'back'), Button.inline('❌ Close menu', b'close') ]] await event.edit(str(CMD_HELP[et]), buttons=fci) else: await event.answer("Please Wait Sir", alert=True) except Exception as e: return await event.edit(str(e))
async def _locked_vote_poll(event: events.CallbackQuery.Event) -> None: global current_vote if not current_vote or current_vote['poll'] != event.message_id: await event.answer('That poll is closed.') return try: await bot( GetParticipantRequest(channel=current_vote["chat"], user_id=event.input_sender)) except UserNotParticipantError: await event.answer('You\'re not participating in the chat.') return weight, displayname = WEIGHTS.get(event.sender_id, (DEFAULT_WEIGHT, None)) if weight == 0: await event.answer('You don\'t have the permission to vote.') return if event.data == b'addsticker/-': weight = -weight displayname = displayname or utils.get_display(await event.get_sender()) try: existing = current_vote['votes'][event.sender_id] if existing.weight == weight: await event.answer(f'You already voted {weight}') return except KeyError: pass current_vote['votes'][event.sender_id] = VoteData( weight=weight, displayname=displayname) scores = calculate_scores() current_vote['score'] = scores.sum if abs(scores.sum) >= VOTES_REQUIRED: current_vote_status.set() accepted = await _locked_finish_poll() res = 'accepted' if accepted else 'rejected' await event.answer(f'Successfully voted {fancy_round(weight)},' f' which made the sticker be {res} \U0001f389') else: await bot.edit_message( current_vote['chat'], current_vote['poll'], POLL_TEMPLATE.format_map(get_template_data()), buttons=[ Button.inline(f'{UP} ({scores.yes_count})', UP_DAT), Button.inline(f'{DOWN} ({scores.no_count})', DOWN_DAT) ], parse_mode='html') await event.answer(f'Successfully voted {weight}')
def get_start(event): text = get_string("pm_menu", "start_hi", event.chat_id) buttons = [[Button.inline(get_string("pm_menu", "btn_help", event.chat_id), 'get_help')]] buttons += [[Button.inline(get_string("pm_menu", "btn_lang", event.chat_id), 'set_lang')]] buttons += [[custom.Button.url(get_string("pm_menu", "btn_chat", event.chat_id), 'https://t.me/YanaBotGroup'), custom.Button.url(get_string("pm_menu", "btn_channel", event.chat_id), 'https://t.me/SophieNEWS')]] return text, buttons
async def echo(event): # Echo the user message. chat = await event.get_input_chat() sender = await event.get_sender() buttons = await event.get_buttons() print(sender.id) print(event.raw_text) # отправка сообщения со встроенными кнопками await event.respond(event.text, buttons=[[Button.inline('Left'), Button.inline("MyLoc")]])
async def lang_command_handler(event: NewMessage.Event, strings): user = await event.get_chat() buttons = [[Button.inline(strings.lang_follow_telegram, data='follow')]] for i in range(0, len(i18n.languages), 3): buttons.append([ Button.inline(i18n.languages[langcode], data=langcode) for langcode in list(i18n.languages.keys())[i:i + 3] ]) db.set_user_state(user, states.SettingLang) await event.respond(strings.lang_select_lang, buttons=buttons)
async def start(event): if event: markup = bot.build_reply_markup([ Button.url(text='📍 My Channel', url="t.me/KanalLinkleri"), Button.url(text='👤 Developer', url="t.me/By_Azade") ]) await bot.send_message(event.chat_id, mesaj, buttons=markup, link_preview=False)
async def lang_command_handler(event: NewMessage.Event, _): user = await event.get_chat() buttons = [ Button.inline(i18n.languages[code], data=code) for code in i18n.langcodes ] buttons = three_buttons_each_line(buttons) buttons.insert( 0, [Button.inline(_('Follow Telegram settings'), data='follow')]) db.set_user_state(user, states.SettingLang) await event.respond(_('Select your language:'), buttons=buttons)
def gen_int_btns(ansrw): buttons = [] for a in [random.randint(1, 20) for _ in range(3)]: while a == ansrw: a = random.randint(1, 20) buttons.append(Button.inline(str(a), data='wc_int_btn:' + str(a))) buttons.insert(random.randint(0, 3), Button.inline(str(ansrw), data='wc_int_btn:' + str(ansrw))) return buttons
async def add_bug(event): if not event.is_reply and len(event.text.split()) == 1: return await event.delete() await bot.send_message( event.chat_id, 'Thanks for your bug report. Please await admin\'s approval', buttons=[ Button.inline("Approve", b'bug'), Button.inline("Reject", b"no" + b'bug') ], reply_to=event.reply_to_msg_id or event)
async def test(event): channel = -1001477006210 global data global data_1 global data_2 # name = get_display_name(event.original_update.user_id) name = await bot.get_entity(PeerUser(event.original_update.user_id)) msg = f"[{name.first_name}](tg://user?id={name.id})" # message_link = f"tg://openmessage?chat_id={event.original_update.peer.channel_id}&message_id={event.original_update.msg_id}" message_link = f"https://t.me/c/{event.original_update.peer.channel_id}/{event.original_update.msg_id}" if event.data.decode('utf-8') == "up": data += 1 buton = tgbot.build_reply_markup([ Button.inline(f"👍🏻 {data}", data="up"), Button.inline(f"❤️ {data_1}", data="kalp"), Button.inline(f"😢 {data_2}", data="agla") ]) await tgbot.edit_message(channel, event.original_update.msg_id, buttons=buton) await bot.send_message( -443785781, f"Tıklayan: {msg}, 👍 e tıkladı.\n\nMesaja git: {message_link}") reply_pop_up_alert = "@RetroTurk Katılımınız İçin Teşekkür Eder." await event.answer(reply_pop_up_alert, cache_time=0, alert=True) # data += 1 if event.data.decode('utf-8') == "kalp": data_1 += 1 buton = tgbot.build_reply_markup([ Button.inline(f"👍🏻 {data}", data="up"), Button.inline(f"❤️ {data_1}", data="kalp"), Button.inline(f"😢 {data_2}", data="agla") ]) await tgbot.edit_message(channel, event.original_update.msg_id, buttons=buton) await bot.send_message( -443785781, f"Tıklayan: {msg}, ❤️ e tıkladı.\n\nMesaja git: {message_link}") reply_pop_up_alert = "@RetroTurk Katılımınız İçin Teşekkür Eder." await event.answer(reply_pop_up_alert, cache_time=0, alert=True) # data_1 += 1 if event.data.decode('utf-8') == "agla": data_2 += 1 buton = tgbot.build_reply_markup([ Button.inline(f"👍🏻 {data}", data="up"), Button.inline(f"❤️ {data_1}", data="kalp"), Button.inline(f"😢 {data_2}", data="agla") ]) await tgbot.edit_message(channel, event.original_update.msg_id, buttons=buton) await bot.send_message( -443785781, f"Tıklayan: {msg}, 😢 e tıkladı.\n\nMesaja git: {message_link}") reply_pop_up_alert = "@RetroTurk Katılımınız İçin Teşekkür Eder." await event.answer(reply_pop_up_alert, cache_time=0, alert=True)
async def handler_pattern_inchat(event): try: global word_in_await word_in_await = True markup_pattern_in_chat = client.build_reply_markup( [[Button.text(pattern_in, resize=True)], [Button.text('Назад', resize=True)]]) await event.respond('Напишите слово для поиска в отобранных чатах!', buttons=markup_pattern_in_chat) except Exception as e: print(e) await event.respond(str(e))
async def all_messages_catcher(event): channel = -1001477006210 if channel: buton = tgbot.build_reply_markup([ Button.inline(f"👍🏻 {data}", data="up"), Button.inline(f"❤️ {data_1}", data="kalp"), Button.inline(f"😢 {data_2}", data="agla") ]) chat = await event.get_chat() admin = chat.admin_rights if admin: await tgbot.edit_message(channel, event.message.id, buttons=buton)