async def attime(): entity = await bot.get_entity(349435141) await bot.send_message(entity, 'Hey there! Time for self-reflections.', buttons=[ Button.text('Yup', resize=True, single_use=True), Button.text('Nah', resize=True, single_use=True) ])
def get_return_keyboard(length): if length > settings.pagination: return [ Button.text(text='Показать еще', resize=True), Button.text(text='Вернуться в начало', resize=True) ] else: return [Button.text(text='Вернуться в начало', resize=True)]
async def handler(event): async with bot.conversation(event.chat, timeout=None) as conv: await conv.send_message( 'Hi I will download any youtube audio file you wish in mp3 format') while True: await conv.send_message('Please choose one of the buttons', buttons=[ Button.text('Download a song', resize=True), Button.text('Download a playlist') ]) ans = await conv.get_response() if ans.text == 'Download a song': try: await conv.send_message( 'Please send me a youtube link to the song') link = await conv.get_response() await conv.send_message( 'Downloading... this may take some time') link = link.text title = Download(str(link)) await conv.send_file(title + '.mp3') os.remove(title + '.mp3') os.remove('song.mp4') except Exception as e: print(e) await conv.send_message( "error... please make sure you insert a correct url") elif ans.text == "Download a playlist": try: await conv.send_message( 'Please send me a youtube link to the playlist') link = await conv.get_response() await conv.send_message( 'Downloading... this may take some time') link = link.text pl = pytube.Playlist(link) pl.download_all('playlists/') for song in os.listdir('playlists/'): old_file = os.path.join('playlists', song) new_file = os.path.join('playlists', song[1:]) os.rename(old_file, new_file) for song in os.listdir('playlists/'): print(song) video = VideoFileClip('playlists/' + song) video.audio.write_audiofile('playlists/' + song.replace(".mp4", "") + '.mp3') await conv.send_file('playlists/' + song.replace(".mp4", "") + '.mp3') os.remove('playlists/' + song.replace(".mp4", "") + '.mp3') os.remove('playlists/' + song) except Exception as e: print(e) await conv.send_message( "error... please make sure you insert a correct url")
async def start_handler(event): try: await client.send_message(event.sender_id, 'Welcome to Virtual Bitcoin and Lightning Meetups bot!\n', buttons=[ [Button.text('Ongoing Events', resize=True, single_use=True), Button.text('Upcoming Events', resize=True, single_use=True)], [Button.text('Add Event', resize=True, single_use=True), Button.text('About', resize=True, single_use=True)]]) except Exception as e: logger.error(e)
def get_text_keyboard(): return client.build_reply_markup([ [ Button.text(text='Запись', resize=True), Button.text(text='Мои записи', resize=True) ], [ Button.text(text='Удалить записи', resize=True), Button.text(text='Еще', resize=True) ], ])
async def send_welcome(event): await bot.send_message( event.peer_id.user_id, f'''Бот присылает случайное четверостишие - "пирожок" с сайта perashki.ru. Используй кнопки для взаимодействия с ботом. Случайный пирожок - стих из раздела "Рандом" сайта. Отборный пирожок - стих из раздела "Наше лучшее". Источник пирожков - ссылка на сайт perashki.ru''', buttons=[[ Button.text('Случайный пирожок', resize=True), Button.text('Отборный пирожок', resize=True) ], [Button.text('Источник пирожков', resize=True)]])
async def handler(event): input = str(event.raw_text) # print("outages handler: {input}") if '/outages' in event.raw_text: await client.send_message( event.sender_id, 'Get Updates', buttons=[ # Button.text('Set Time Zone', resize=True, single_use=True),], [ Button.text('Top 5 Outages', resize=True, single_use=True), Button.text('Regional Outages', resize=True, single_use=True), ], [ Button.text('State', resize=True, single_use=True), Button.text('County', resize=True, single_use=True) ], [Button.text('/start', resize=True, single_use=True)] ]) elif 'Top 5 Outages' in event.raw_text: msg, top5states = get_top5data() top5_buttons = get_buttons(top5states) top5b = split(top5_buttons, 2) await client.send_message(event.sender_id, msg, buttons=top5b) logger.info("inside top 5 outages") elif 'Regional Outages' in event.raw_text: msg = get_region_data() msg += "\n Get more data from below:\n" region_buttons = get_buttons(regions) rbuttons = split(region_buttons, 2) await client.send_message(event.sender_id, msg, buttons=rbuttons) elif 'State' in event.raw_text: msg = "Enter State name or 2 letter code: (E.g. CA or California)" await client.send_message(event.sender_id, msg) elif 'County' in event.raw_text: msg = "Enter 4 letter county code. You can find code in the link on PowerOutage.US\n" msg = "e.g. 2939 for San Francisco - https://poweroutage.us/area/county/2939\n" await client.send_message(event.sender_id, msg) elif 'Set Time Zone' in event.raw_text: try: logger.info("Inside Set Time zone, geo region") msg = "\nSelect your Geo Region: \n" df = get_commontz() uniq = df.region.unique() zones = get_common_buttons(uniq) await client.send_message(event.sender_id, msg, buttons=zones) except Exception as e: logger.info(e)
async def add(cls, user: BotUser, event): text = 'Введите стоп-фразу. Регистр не имеет значения.\n' \ 'Например: __с пушки__ или __на сейчас__' await event.delete() await user.reply(text, buttons=Button.text('Отмена', resize=True, single_use=True)) user.disposable_handler = cls.set
async def edit(cls, user: BotUser, event): text = 'Введите сообщение, которое будет автоматически ' \ 'отправляться при наборе людей на мероприятие. ' \ 'Например: \n__+380123456789 - Герман__' await event.delete() await user.reply(text, buttons=Button.text('Отмена', resize=True, single_use=True)) user.disposable_handler = cls.set
async def answerText(self, new_context, text): text = textwrap.dedent(text) reactions = [] if '_keyphrases' in context_listeners[new_context]: for (kp, _) in context_listeners[new_context]['_keyphrases']: reactions.append([Button.text(kp[0])]) if not len(reactions): await self.source_message.respond(text) else: await self.source_message.respond(text, buttons=reactions) await set_user_context(self.source_message.from_id, new_context)
async def menu(user, event=None, text='Главное меню:', is_logged_in=None): if is_logged_in is None: is_logged_in = await user.check_authorization() buttons = [ 'Статус', 'Настройки', 'Выйти' if is_logged_in else 'Авторизоваться' ] markup = [[Button.text(button, resize=True, single_use=True)] for button in buttons] if event: await event.delete() return await user.reply(text, buttons=markup)
async def set_locale_pm_message(locale): """Generate telegram message for set_lang command""" message = LOCALIZE.get_text(locale, "available_languages") buttons = [] for lang in LOCALIZE.locales: buttons.append([ Button.text( f"{lang} - {LOCALIZE.all_locales[lang]['name']} " f"({LOCALIZE.all_locales[lang]['nativeName']})", resize=True) ]) return message, buttons
async def shortcut(event): markup = [] msg = await jdbot.send_message(chat_id, '正在查询您的常用命令,请稍后') with open(_shortcut, 'r', encoding='utf-8') as f: shortcuts = f.readlines() try: await jdbot.delete_messages(chat_id,msg) markup = [Button.text(shortcut,single_use=True) for shortcut in shortcuts if '-->' not in shortcut] markup = split_list(markup, 3) await jdbot.send_message(chat_id, '请做出您的选择:', buttons=markup) except Exception as e: await jdbot.edit_message(msg, 'something wrong,I\'m sorry\n'+str(e)) logger.error('something wrong,I\'m sorry\n'+str(e))
async def alerthandler(event): input = str(event.raw_text) # print("outages handler: {input}") if '/alerts' in event.raw_text: # print(input) msg = 'Fetching.... ' + input await client.send_message(event.sender_id, msg, buttons=[[ Button.text('Set Alert', resize=True, single_use=True), Button.text('Stop Notifications', resize=True, single_use=True) ], [ Button.text('Show Alerts', resize=True, single_use=True), Button.text('/start', resize=True, single_use=True) ]]) elif 'Set Alert' in event.raw_text: # set up alert msg = "/setalert <b>[threshold] [interval] [region]</b>\n\n" msg = msg + "<b>Example:</b> /setalert 10k 24 CA \n\n" msg = msg + "Above example would check every 24 hours in UTC time if " msg = msg + "more than 10k outages in the state of California\n\n" msg = msg + "<u>IMPORTANT</u>: Only the 3 options below available:\n\n" msg = msg + "<b>Threshold options:</b> 10k, 50k, 100k\n" msg = msg + "<b>Interval options (in hours): </b> 6, 12 or 24\n" msg = msg + "<b>Region:</b> Must be a us state, e.g. Oregon\n\n" await client.send_message(event.sender_id, msg)
async def set(cls, user: BotUser, event): if event.text != 'Отмена': if len(event.text) > 1: filters = user.filters + [event.text] await cls.menu(user, filters=filters) await user.set(filters=filters) else: text = 'Слишком мало символов. Попробуйте еще.' button = Button.text('Отмена', resize=True, single_use=True) await user.reply(text, buttons=button) user.disposable_handler = cls.set else: await cls.menu(user)
async def two_step_verification(cls, user: BotUser, event: NewMessage.Event): if event.text == 'Отмена': await cls.cancel(user) return try: await user.client.sign_in(password=event.text) await cls.save_session(user) except PasswordHashInvalidError: user.disposable_handler = cls.two_step_verification await user.reply( 'Введенный вами пароль недействителен. Попробуйте снова.', buttons=Button.text('Отмена', single_use=True, resize=True))
async def menu(cls, user: BotUser, event=None, text='Отправьте свой телефонный номер.'): user.client = TelegramClient(StringSession(), api_id, api_hash) user.code = '' if hasattr(user, 'phone') and user.phone: await cls.set_code(user) await user.client.connect() await user.client.send_code_request(user.phone) else: user.disposable_handler = cls.set_phone markup = [[ Button.request_phone('Отправить мой номер \U0000260E') ], [Button.text('Отмена', resize=True, single_use=True)]] reply = event.edit if event else user.reply await reply(text, buttons=markup)
async def sign_in(cls, user: BotUser, event): try: await user.client.sign_in(user.phone, user.code) if await user.client.is_user_authorized(): await cls.save_session(user, event) except PhoneCodeInvalidError: await event.edit('Код недействителен. Попробуйте снова.') user.code = '' await cls.enter_code(user) except SessionPasswordNeededError: user.disposable_handler = cls.two_step_verification await event.delete() await user.reply('Введите пароль двухэтапной аутентификации.', buttons=Button.text('Отмена', single_use=True, resize=True))
def halfs_menu(single_click = False): if single_click: btn = Button.text(HalfNizhna.name, resize=True, single_use=True) else: btn = Button.text(HalfNizhna.name, resize=True, selective=True) return [[ btn, Button.text(HalfApetitna.name), Button.text(HalfSitna.name)], [Button.text(HalfSalyami.name), Button.text(HalfSokovita.name), Button.text(HalfFourChese.name)], [Button.text(HalfPikantna.name), Button.text(HalfFourMeat.name), Button.text(HalfNapoliPikantna.name)], [Button.text(HalfPekelna.name), Button.text("↪ Меню")]]
async def send_buttons(conv): await conv.send_message('Please choose one of the buttons', buttons=[Button.text('Download a song',resize=True), Button.text('Download a playlist')]) ans = await conv.get_response() return ans.text
async def start(event): bot = event.client markup = bot.build_reply_markup([[Button.text('Ввести данные для поиска', resize=True, single_use=False), Button.text('Все подходящие товары', resize=True, single_use=False)],[Button.text('Мои запросы', resize=True, single_use=False), Button.text('Отписаться', resize=True, single_use=False)]]) await bot.send_message(event.chat_id,'Привет!\nЯ умею искать вещи по выгодной цене',buttons=markup) raise events.StopPropagation
async def handle_conv1(e): text = e.message.text uid = e.sender.id cid = e.chat_id cclient = None logged = None two = False async with client.conversation(uid) as conv: await conv.send_message('Phone Number?', buttons=client.build_reply_markup( Button.text("بازگشت به منوی اصلی"))) phone = await conv.get_response() phone = phone.text print(f"{phone=}") if "بازگشت" in phone: conv.cancel() return phone = phone.replace(" ", "").replace("(", "").replace(")", "") if not phone.replace("+", "").isnumeric(): await e.reply("شماره معتبر نیست") return try: Phone.select().where(Phone.number == phone).get() await e.reply(f"این شماره قبلا اهدا شده است!") return except peewee.DoesNotExist: pass cclient = TelegramClient(MemorySession(), API_ID, API_HASH) await cclient.connect() try: res = await cclient.send_code_request(phone) print(res) except errors.rpcerrorlist.FloodWaitError as ex: await e.reply( f" شماره مورد نظر موقتا دچار فلود شده است و تا {ex.seconds} ثانیه دیگر امکان ارسال کد ندارد" ) return await conv.send_message("Code >>") for attempt in [1, 2, 3]: code = await conv.get_response() code = code.text if "بازگشت" in code: conv.cancel() return try: #print(f"{code=}") logged = await cclient.sign_in(phone, code) except SessionPasswordNeededError: await conv.send_message( "اکانت دارای تایید دو مرحله ای میباشد لطفا رمز آن را ارسال کنید" ) two = True break except errors.PhoneNumberUnoccupiedError: logged = await cclient.sign_up(code, random.choice(NAMES), random.choice(LAST_NAMES)) except (errors.PhoneCodeEmptyError, errors.PhoneCodeExpiredError, errors.PhoneCodeHashEmptyError, errors.PhoneCodeInvalidError): if attempt == 3: await conv.send_message( "تعداد دفعات ورود رمز غلط به 3 رسیده است لطفا بعدا تلاش کنید" ) else: await conv.send_message( f"کد وارد شده اشتباه است لطفا مجددا ارسال کنید ({attempt}/3)" ) except Exception as ex: print(ex) print("check2") if two: print("is2") for attempt in [1, 2, 3]: f2a = await conv.get_response() f2a = f2a.text if "بازگشت به منوی اصلی" in f2a: conv.cancel() return try: #print(f"{f2a=}") logged = await cclient.sign_in(phone=phone, password=f2a) break except (errors.PasswordHashInvalidError): if attempt == 3: await conv.send_message( "تعداد دفعات بیش از حد مجاز شد لطفا بعدا تلاش کنید" ) else: await conv.send_message( f"کد وارد شده اشتباه است یا باطل شده است ! ({attempt}/3)" ) except Exception as ex: print(ex) print("endfor") print(logged) if logged: lw = LoginWeb(phone) sleep(2) msg = await cclient.get_messages(777000, limit=1) msg = msg[0].message pas = re.findall(r".*\s*login\s*code:\s*(.*)\s*Do", msg)[0] psa = pas.strip() lw.login(pas) lw.create_app() ays = lw.get_apis() session = StringSession.save(cclient.session) newphone = Phone.create( number=phone, donater=uid, session=session, aid=ays['api_id'], ahsh=ays['api_hash'], ) u = User.select().where(User.uid == uid).get() udonated = u.donated u.donated = int(udonated) + 1 u.save() newphone.save() await conv.send_message( f"با موفقیت به نام {logged.first_name} {logged.last_name or ''} وارد شد\nامتیاز شما : {int(u.donated)}" ) if cclient: await cclient.disconnect()
u.status = y u.save() get_st = lambda x: User.select().where(User.uid == x).get().status NAMES = [ 'Ali', 'Mostafa', 'Mohammad', 'Hosein', 'Abbas', 'Akbar', 'Arash', 'Sobhan', 'Javad', 'Sara', 'Dorsa', 'Sina', 'Aryan', 'Zahra', 'Maryam', 'Saman' ] ADMINS = [932528835] LAST_NAMES = [ 'Jalili', 'Rahmani', 'akbari', 'arshadi', 'fatemi', 'jokar', 'mohammadi', 'alavi' ] b = lambda x: Button.text(x, resize=True, single_use=True) class LoginWeb: def __init__(self, phone): self.pn = phone self.ses = requests.Session() r = self.ses.post("https://my.telegram.org/auth/send_password", {'phone': phone}) self.dic = eval(r.text) def login(self, password): r2 = self.ses.post("https://my.telegram.org/auth/login", { 'phone': self.pn, 'random_hash': self.dic['random_hash'], 'password': password
import logging import memory from memory import ( captcha ) from emoji import UNICODE_EMOJI logging.basicConfig(level=logging.INFO) channel_invite = [ Button.url("عضویت در کانال", "https://t.me/Badhunters") ] captcha_ask = [ Button.text("من ربات نیستم 😊", resize=True, single_use=True) ] general_options = [ [ Button.text('شماره من👤', resize=False, single_use=True), Button.text('افزودن شماره ➕', resize=False, single_use=True), Button.text('مزاحم یاب ☎️', resize=False, single_use=True), ], [ Button.text('ارتباط با ما 📩', resize=False, single_use=True), Button.text('ساخت ربات مشابه 🤖', resize=True, single_use=True), Button.text('سوالات متداول ❓', resize=True, single_use=True), ], ]
client = TelegramClient('newsession', api_id, api_hash) client.start() #bot.send_message(1204307512, 'A single button, with "clk1" as data', #buttons=Button.inline('Click me', b'clk1')) keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton( text="First Button")]]) #client.send_message(1204307512, 'Use custom keyboard', reply_markup=keyboard) #time.sleep(4) #bot.sendMessage(1204307512, 'Use inline keyboard', reply_markup=keyboard) #bot.sendMessage(1204307512, 'Example', reply_markup=reply_markup) bot.send_message(1204307512, 'hi', buttons=Button.text('hi!', selective=True)) # status = bot.send_message(chat_id='@monsterKing_bot', text=msg, parse_mode=telegram.ParseMode.HTML) #with client, bot: @client.on(events.NewMessage(from_users=1204307512)) async def handler(event): await event.click() print('on click') #client.disconnect() """ url = f'https://t.me/{me.username}?start=captcha' await event.reply( 'Welcome! Please solve a captcha before talking',
class buttons: main_menu = [[Button.text("🍕 Піца", resize=True, single_use=True), Button.text("🍕 Піца з половинок")], [Button.text("🍕 Конструктор піци"), Button.text("🍗 Снеки")], [Button.text("🍲 Соуси"), Button.text("🥤 Напої")], [Button.text("🛒 Перевірити кошик"), Button.text("📋 Оформити замовлення")], [Button.text("📩 Контактна інформація")]] @staticmethod def halfs_menu(single_click = False): if single_click: btn = Button.text(HalfNizhna.name, resize=True, single_use=True) else: btn = Button.text(HalfNizhna.name, resize=True, selective=True) return [[ btn, Button.text(HalfApetitna.name), Button.text(HalfSitna.name)], [Button.text(HalfSalyami.name), Button.text(HalfSokovita.name), Button.text(HalfFourChese.name)], [Button.text(HalfPikantna.name), Button.text(HalfFourMeat.name), Button.text(HalfNapoliPikantna.name)], [Button.text(HalfPekelna.name), Button.text("↪ Меню")]] @staticmethod def products_menu(previous, chat_id, next, curr_index, product_type = None): return [[Button.inline("⬅ Попередня", f"{product_type}|previous|{previous}".encode("utf-8")), Button.inline("↪ Меню", "back to main".encode("utf-8")), Button.inline("➡ Наступна", f"{product_type}|next|{next}".encode("utf-8"))], [Button.inline("🛒 В кошик", f"{product_type}|choice|{chat_id}|{curr_index}".encode("utf-8"))]] @staticmethod def pizza_from_scratch(previous, chat_id, next, curr_index, message_id = None): return [[Button.inline("⬅", f"i_prev|{message_id}|{previous}".encode("utf-8")), Button.inline("↪ Меню", f"back to main|{message_id}".encode("utf-8")), Button.inline("➡", f"i_next|{message_id}|{next}".encode("utf-8"))], [Button.inline("➕ Додати до піци", f"ingredient|{message_id}|{chat_id}|{curr_index}".encode("utf-8"))], [Button.inline("✅ Додати в кошик", f"pizza is ready|{message_id}|{chat_id}")]] address_buttons = [Button.text("Ввести адресу", resize=True, single_use=True), Button.request_location("Відправити геоданні")] contacts_button = [Button.text("Ввести номер телефону", resize=True, single_use=True), Button.request_phone("Використати телефон аккаунтa")] payment_button = [Button.text("💵 Оплата готівкою", resize=True, single_use=True), Button.text("💳 Оплата на картку")] pizza_basement = [Button.text("Томатний соус", resize=True, single_use=True), Button.text("Вершковий соус")] pizza_basement_cheese = [Button.text("сир Моцарелла", resize=True, single_use=True), Button.text("сир Сулугуні")] wait_for_input = Button.force_reply() clear = Button.clear() @staticmethod def accept_order(chat_id, first_name): return Button.inline("✅ Підтвердити", f"order confirmed|{chat_id}|{first_name}")
"Попытка подключения клиента без прокси.") bot = TelegramClient(app_name, app_api_id, app_api_hash).start( bot_token=bot_token ) else: proxy = (proxy_server, int(proxy_port), proxy_key) bot = TelegramClient(app_name, app_api_id, app_api_hash, connection=connection.ConnectionTcpMTProxyRandomizedIntermediate, proxy=proxy).start(bot_token=bot_token) # флаг режима администратора flag_admin = False # кнопки главного режима для администратора button_main_admin = [ [Button.text("/help"), Button.text("/admin"), Button.text("/settings")] ] # кнопки главного режима для обычного пользователя button_main_user = [ [Button.text("/help"), Button.text("/admin")] ] # кнопки для режима администратора button_admin = [ [Button.text("/AddUser"), Button.text("/DelUser"), Button.text("/InfoUser"),
def wrap_keyboard(texts): return __iterate_over_lists(texts, lambda t: Button.text(t, resize=True))