from tgficbot.states import onstate from tgficbot import strings logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) config = configparser.ConfigParser() config.read(os.path.expanduser('~/.config/tgficbot.cfg')) bot = TelegramClient( 'bot', config['api']['id'], config['api']['hash']).start(bot_token=config['bot']['token']) @bot.on(NewMessage(pattern='/start')) async def start_command_handler(event: NewMessage.Event): if event.is_private: await event.respond(strings.greeting) chat = await event.get_chat() db.save_user(chat) db.conn.commit() raise StopPropagation @bot.on(NewMessage(pattern='/add')) @onstate(states.Empty) async def add_command_handler(event): await event.respond(strings.add_guide) user = await event.get_chat() db.set_user_state(user, states.AddingAChannel)
import asyncio from telethon import events from telethon.events import NewMessage from core import misc from core.hints import EventLike from .task import Task @events.register(NewMessage(outgoing=True, pattern=r'\.time$')) async def time_status(event: EventLike): if Task.is_running(): await event.edit('Time task is running') else: await event.edit('Time task is not running') @events.register( NewMessage(outgoing=True, pattern=r'\.time (?P<mode>(on|off))$')) async def time_toggle(event: EventLike): mode = event.pattern_match.group('mode') == 'on' if mode: if Task.is_running(): await event.edit('Time task was already running') else: await asyncio.gather(Task.start(), event.edit('Time task has been started')) else: if not Task.is_running():
with bot: if OTOMATIK_KATILMA: try: bot(JoinChannelRequest("@AsenaUserBot")) bot(JoinChannelRequest("@AsenaRemaster")) except: pass moduller = CMD_HELP me = bot.get_me() uid = me.id try: @tgbot.on(NewMessage(pattern='/start')) async def start_bot_handler(event): if not event.message.from_id == uid: await event.reply( f'`Merhaba ben` @AsenaUserBot`! Ben sahibime (`@{me.username}`) yardımcı olmak için varım, yaani sana yardımcı olamam :/ Ama sen de bir Asena açabilirsin; Kanala bak` @AsenaUserBot' ) else: await event.reply(f'`Tengri save Turks! Asena working... 🐺`') @tgbot.on(InlineQuery) # pylint:disable=E0602 async def inline_handler(event): builder = event.builder result = None query = event.text if event.query.user_id == uid and query == "@AsenaUserBot": rev_text = query[::-1]
def __init__(self, watcher: SubscriptionWatcher): commands = [self.add_sub_cmd, self.remove_sub_cmd, self.list_sub_cmd] + self.pause_cmds + self.resume_cmds commands_pattern = re.compile(r"^/(" + "|".join(re.escape(c) for c in commands) + ")") super().__init__(NewMessage(pattern=commands_pattern, incoming=True)) self.watcher = watcher
from telethon import Button from telethon.events import NewMessage, CallbackQuery, StopPropagation from .. import bot, users search_buttons = [ [ Button.switch_inline("Search track 🎧", same_peer=True), Button.switch_inline("Search album 💽", query=".a: ", same_peer=True), ], [Button.inline("❌")], ] @bot.on(NewMessage(pattern="/settings")) async def settings(event: Union[NewMessage.Event, CallbackQuery.Event]): if hasattr(event, "query"): answer = event.edit else: answer = event.respond await answer( "Settings:", buttons=[[Button.inline("Quality 🎧", data="q")], [Button.inline("❌")]], ) raise StopPropagation @bot.on(CallbackQuery(pattern="q")) async def settings_quality(event: CallbackQuery.Event): q = users[event.query.user_id]["quality"]
subprocess.call("pip install bwb".split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE) from telethon.events import NewMessage from bwb import bwb import asyncio bwb = bwb.bwb(borg.uid) wrap_users = { 't': 79316791, # Tanner 'j': 172033414, # Jason 'o': 358491576, # Jonas 'm': 964048273, # Mini Eule 'g': 234480941, # Twit 'v': 181585055, # Viktor } @borg.on(NewMessage(outgoing=True, pattern='!!add wrap (?:(\w+)(?: (\d+))?)?')) async def add_user(event): rep = await event.get_reply_message nick = event.pattern_match.group(1) userid = event.pattern_match.group(2) if userid is None and rep != None: userid = rep.from_id elif userid is None and rep is None: await event.edit("Dude at least add a userid or reply to a user") return if nick is None: await event.edit("Give a userid") return wrap_users[nick] = int(userid) await event.edit("User `{}` with user id `{}` has been added".format(nick, str(userid)))
async def send_detected(text: str, event: Event): try: detected: Detected = await detect(text) text = f'Language: {detected.lang}\n' \ f'Confidence: {detected.confidence}' except Exception as ex: text = str(ex) if event.out: await event.edit(text) else: await event.reply(text) @events.register(NewMessage(outgoing=True, pattern=Patterns.tr_help)) async def tr_help(event: Event): await event.edit(f'```Nailerine translator module\n\n' f'.tr text\n' f'.tren text\n' f'.tren-uk text') @events.register( NewMessage(outgoing=True, pattern=Patterns.tr_reply, func=lambda e: e.is_reply)) async def tr_reply(event: Event): reply_message = await event.get_reply_message() text = reply_message.raw_text if not text:
deezer = deethon.Session(DEEZER_TOKEN) logger.debug(f'Using deethon v{deethon.__version__}') bot = TelegramClient(__name__, API_ID, API_HASH, base_logger=telethon_logger).start(bot_token=BOT_TOKEN) logger.info("Bot started") # Saving user preferences locally users = {} bot.loop.run_until_complete( bot( functions.bots.SetBotCommandsRequest(commands=[ types.BotCommand(command='start', description='Get the welcome message'), types.BotCommand(command='help', description='How to use the bot'), types.BotCommand(command='settings', description='Change your preferences'), types.BotCommand( command='info', description='Get some useful information about the bot'), types.BotCommand(command='stats', description='Get some statistics about the bot'), ]))) @bot.on(NewMessage()) async def init_user(event: NewMessage.Event): if event.chat_id not in users.keys(): users[event.chat_id] = {"quality": "FLAC"}
if user.last_name is not None: lines.append(f' last: <code>{escape(user.last_name)}</code>') if user.username is not None: lines.append(f' username: @{user.username}') if user.bot: lines.append(f' bot: <code>{user.bot}</code>') if user.scam: lines.append(f' scam: <code>{user.scam}</code>') if user.fake: lines.append(f' fake: <code>{user.fake}</code>') lines.append(f' <a href="tg://user?id={user.id}">link</a>') return lines @client.on(NewMessage(func=lambda e: e.is_private, incoming=True)) async def private_message(event): await event.reply('Hi, I help with reporting spam in @SpamBlockers.') @client.on( NewMessage( func=lambda e: e.is_group and e.is_channel, pattern=(r'^/r (?:https?://)?(?:t\.me|' r'telegram\.(?:dog|me))/(\w+)/(\d+)$'), ), ) async def on_report(event): chat = event.pattern_match.group(1) id = int(event.pattern_match.group(2)) message = await user.get_messages(chat, ids=id)
client = TelegramClient(StringSession(config.session), config.api_id, config.api_hash) async def format_time(seconds: int) -> str: minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) string = (((str(days) + " day(s), ") if days else "") + ((str(hours) + " hour(s), ") if hours else "") + ((str(minutes) + " minute(s), ") if minutes else "") + ((str(seconds) + " second(s), ") if seconds else "")) return string[:-2] @client.on(NewMessage(outgoing=True)) async def scanner(event: NewMessage.Event): global N_WORD_TIME, SAID_TIMES text = event.message.text if re.findall(r"(n|i|e){1,32}((g{2,32}|q){1,32}|[rgq]{2,32})[aoe3r]{1,32}", text.lower()): n_time = await format_time(int(time.time() - N_WORD_TIME)) SAID_TIMES += 1 await event.reply( "`ANTI-N-WORD BOT`\n**restting the timer because you said the N-word.**\n" "your record: %s" % n_time) N_WORD_TIME = time.time() @client.on(NewMessage(outgoing=True, pattern=r"^\.(status|stats)$")) async def stats(event: NewMessage.Event):
from telethon.tl.custom import Message from telethon.tl.types import MessageEntityPre, MessageEntityCode from core import misc from .utils import paste log = logging.getLogger(__name__) Event = Union[NewMessage.Event, Message] class AutoPaste: enabled = True @events.register(NewMessage(outgoing=True, pattern=r'\.paste .+')) @events.register(MessageEdited(outgoing=True, pattern=r'\.paste .+')) async def inline_paste(event: Event): code = event.raw_text.replace('.paste ', '') url = await paste(code) await event.edit(url, link_preview=False) @events.register( NewMessage(outgoing=True, pattern=r'\.paste$', func=lambda e: e.is_reply)) @events.register( MessageEdited(outgoing=True, pattern=r'\.paste$', func=lambda e: e.is_reply)) async def reply_paste(event: Event): reply = await event.get_reply_message()
from datetime import timedelta from aiojobs import create_scheduler from telethon import TelegramClient from telethon.events import register, NewMessage from core import hints from core.misc import handlers from modules.nailerine.wipers.omw.util import omw, periodic_omw chats: hints.OmwChats = {} @register(NewMessage(outgoing=True, pattern=r'omw$')) async def omw_status(event: NewMessage.Event): client: TelegramClient = event.client offset = timedelta(days=-2) messages = await client.get_messages(await event.get_input_chat(), limit=0, offset_date=offset) text = f'OMW is {"enabled" if event.chat_id in chats else "disabled"} in this chat\n' text += f'There are {messages.total} old messages (48 hours offset)' await event.edit(text) @register(NewMessage(outgoing=True, pattern=r'omw now$')) async def omw_now(event: NewMessage.Event): result = await omw(event)
from asyncio import sleep from random import randint from telethon import TelegramClient from telethon.events import register, NewMessage from core.misc import handlers @register(NewMessage(outgoing=True, pattern=r'wom$')) async def wipe_own_messages(event: NewMessage.Event): client: TelegramClient = event.client entity = await event.get_input_chat() me = await client.get_me(True) messages = [] count = 0 async for message in client.iter_messages(entity, from_user=me): messages.append(message) if len(messages) >= 100: await client.delete_messages(entity, messages) count += len(messages) messages = [] await sleep(randint(1, 5)) if messages: await client.delete_messages(entity, messages) count += len(messages) report = await client.send_message(me, f'Nailerine has sent {count} deletion requests')
import deethon from telethon.events import NewMessage, StopPropagation from telethon.tl.types import DocumentAttributeAudio, InputStickerSetID from .. import bot, users, deezer from ..helper.download_status import DownloadStatus from ..helper.upload_status import UploadStatus from ..utils import translate from ..utils.fast_download import upload_file @bot.on(NewMessage(pattern=r"https?://(?:www\.)?deezer\.com/(?:\w+/)?track/(\d+)")) async def track_link(event: NewMessage.Event): try: track = deethon.Track(event.pattern_match.group(1)) except deethon.errors.DeezerApiError: await event.reply("Track not found.") raise StopPropagation await event.respond( translate.TRACK_MSG.format( track.title, track.artist, track.album.title, track.release_date ), file=track.album.cover_xl) quality = users[event.chat_id]["quality"] download_status = DownloadStatus(event) await download_status.start() file = await bot.loop.run_in_executor(None, deezer.download_track, track, quality, download_status.progress) download_status.finished()
import logging import pickle from os import execl, path, remove from sys import executable from telethon.events import NewMessage from .. import bot, OWNER_ID logger = logging.getLogger(__name__) if path.exists('restart.pickle'): with open('restart.pickle', 'rb') as status: chat, msg_id = pickle.load(status) bot.loop.run_until_complete( bot.edit_message(chat, msg_id, "Restarted Successfully!")) remove('restart.pickle') @bot.on(NewMessage(pattern='/restart')) async def restart(event): restart_message = await event.reply("Restarting, Please wait!") with open('restart.pickle', 'wb') as status: pickle.dump([event.chat_id, restart_message.id], status) logger.info('Restarting deegram') execl(executable, executable, "-m", "deegram")
from telethon import Button, events from telethon.events import NewMessage, StopPropagation from . import bot, botStartTime, logger, plugins from .utils import translate, fetch from .utils.bot_utils import get_readable_file_size, get_readable_time plugins.load() inline_search_buttons = [[ Button.switch_inline(translate.SEARCH_TRACK, same_peer=True), Button.switch_inline(translate.SEARCH_ALBUM, query=".a ", same_peer=True) ], [Button.inline('❌')]] @bot.on(NewMessage(pattern='/start')) async def start(event: NewMessage.Event): await event.reply(translate.WELCOME_MSG, buttons=inline_search_buttons) raise StopPropagation @bot.on(NewMessage(pattern='/help')) async def get_help(event: NewMessage.Event): await event.reply(translate.HELP_MSG) @bot.on(NewMessage(pattern='/info')) async def info(event: NewMessage.Event): await event.reply(translate.INFO_MSG) raise StopPropagation
def handlers(self): yield from { NewMessage(pattern='/greet'): self.greet, NewMessage(pattern=f'.*(@{self.bot.name}).*'): self.respond }.items()
for folder in folders: if (not os.path.exists(folder)): os.mkdir(folder) if (not os.path.exists('channels/ids')): open('channels/ids', 'w').write('') if (not os.path.exists('logs')): open('logs', 'w').write('Nothing\n') open('running', 'w').write('no') logging.basicConfig( format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING) @client.on(NewMessage()) async def get_id(event: newmessage.NewMessage.Event): text = str(event.message.message) cid = event.chat_id if (text == "id"): await event.reply(f"`{cid}`") @client.on(NewMessage(from_users=SUDOS)) async def admins(event: newmessage.NewMessage.Event): text = str(event.message.message) print(text) if (text.startswith("##")): command = text.replace("##", "").strip() x = os.popen(command).read() await event.reply(f"**{command}**\n\n`{x}`")
finished = asyncio.get_event_loop().create_future() @bot.on(CallbackQuery(data=b'confirm_continue')) async def proceed_continue(_): newbutton = Button.inline("✅", 'dummy') await message.edit(buttons=newbutton) bot.remove_event_handler(proceed_continue) finished.set_result(True) raise events.StopPropagation await finished # asyncio.get_event_loop().stop() # ? @bot.on(NewMessage(pattern='/start|/help')) async def process_game(_): @bot.on(NewMessage(pattern='/help')) async def send_help_message(event): text = """Привет! Это — бот "Мафия". \ Начало игры: при помощи команды `/start количество_игроков` """ event.respond(text) global players _event = None @bot.on(NewMessage(pattern='/start')) async def start(_event): """Начало игры по вводу команды /start <n>.""" nonlocal event
from telethon.events import NewMessage from bwb import bwb import asyncio bwb = bwb.bwb(borg.uid) wrap_users = { 't': 79316791, # Tanner 'j': 172033414, # Jason 'o': 358491576, # Jonas 'm': 964048273, # Mini Eule 'g': 234480941, # Twit 'v': 181585055, # Viktor } @borg.on(NewMessage(outgoing=True, pattern='!!add wrap (?:(\w+)(?: (\d+))?)?')) async def add_user(event): rep = await event.get_reply_message nick = event.pattern_match.group(1) userid = event.pattern_match.group(2) if userid is None and rep != None: userid = rep.from_id elif userid is None and rep is None: await event.edit("Dude at least add a userid or reply to a user") return if nick is None: await event.edit("Give a userid") return wrap_users[nick] = int(userid) await event.edit("User `{}` with user id `{}` has been added".format( nick, str(userid)))
async def process_game(_): @bot.on(NewMessage(pattern='/help')) async def send_help_message(event): text = """Привет! Это — бот "Мафия". \ Начало игры: при помощи команды `/start количество_игроков` """ event.respond(text) global players _event = None @bot.on(NewMessage(pattern='/start')) async def start(_event): """Начало игры по вводу команды /start <n>.""" nonlocal event global players event = _event text = event.text try: pattern = r'/start[^\s]*\s+(\d+)' number = int(re.fullmatch(pattern, text).group(1)) except (AttributeError, ValueError) as e: await event.respond( 'Начало игры: ввод количества игроков' f' (от {MIN_PEOPLE} до {MAX_PEOPLE})\n' 'Формат сообщения: /start число.\n' 'Число — количество игроков' ) raise events.StopPropagation game_init = GameInit() try: players = game_init.randomize_roles(number) except GameError: await event.respond('Слишком много/мало людей') raise events.StopPropagation return msg = '\n'.join(str(x + 1) + '. ' + str(y) for x, y in enumerate(players)) await event.respond(msg) await confirm_start() event = _event del _event async def confirm_start(): global players nonlocal event event = await event.respond('Маякни, когда ты прочитаешь, передашь и все познакомятся') finished = asyncio.get_event_loop().create_future() # builder = event.builder button = Button.inline('Далее', b'confirm_start') # buttons = builder.article(buttons=[button]) # @bot.on(CallbackQuery(data='confirm_start')) await event.edit(buttons=[button]) # test start ''' @bot.on(NewMessage) async def test_echo(event): print(type(event), event) # test end ''' @bot.on(CallbackQuery(data=b'confirm_start')) async def start_game(event_): global players await event.edit(text=event.text + '\n\n✅Продолжено') game_loop = GameLoop(players, event) await game_loop.start(event) bot.remove_event_handler(start_game) # await event.respond('Знакомство мафии. Выделенное время: 1 минута') finished.set_result(True) raise events.StopPropagation # event.respond(msg, buttons=buttons) await finished raise events.StopPropagation
def decorator(function): if not function: return None if not callable(function): return None caller = getouterframes( currentframe(), 2)[1] # get caller in case of failed actions caller = f"{basename(caller.filename)[:-3]}:{caller.lineno}" # link to file and line number if not command: self.log.error( f"Command in function '{function.__name__}' must not be empty ({caller})" ) return None if not self.__checkCmdValidity(command): self.log.error(f"Validity check for '{command}' in function '{function.__name__}' "\ f"failed. Special characters are not allowed ({caller})") return None if alt and not self.__checkCmdValidity(alt): self.log.error(f"Validity check for '{alt}' (alternative command of '{command}') "\ f"in function '{function.__name__}' failed. "\ f"Special characters are not allowed ({caller})") return None if not pre_register_cmd(command, alt, hasArgs, ".", False, False, function): self.log.error(f"Unable to add command '{command}' in function '{function.__name__}' "\ f"to event handler as previous registration failed ({caller})") return None async def func_callback(event): try: await function(event) except Exception as e: # This block will be executed if the function, where the events are # being used, has no own exception handler(s) try: # get current executed command curr_cmd = event.pattern_match.group(0).split( " ")[0][1:] except: curr_cmd = command self.log.error( f"Command '{curr_cmd}' stopped due to an unhandled exception " f"in function '{function.__name__}'", exc_info=True if self.traceback else False) try: # in case editing messages isn't allowed (channels) await event.edit( f"`{msgResp.CMD_STOPPED.format(f'{curr_cmd}.exe')}`" ) except: pass if alt: cmd_regex = fr"^\.(?:{command}|{alt})(?: |$)(.*)" if hasArgs else fr"^\.(?:{command}|{alt})$" else: cmd_regex = fr"^\.{command}(?: |$)(.*)" if hasArgs else fr"^\.{command}$" try: if not ignore_edits: tgclient.add_event_handler( func_callback, MessageEdited(pattern=cmd_regex, *args, **kwargs)) tgclient.add_event_handler( func_callback, NewMessage(pattern=cmd_regex, *args, **kwargs)) except Exception as e: self.log.error(f"Failed to add command '{command}' to client "\ f"(in function '{function.__name__}' ({caller}))", exc_info=True if self.traceback else False) return None return func_callback
class YoutubeDownloaderBot: def __init__(self, api_id: int, api_hash: str, bot_token: str, *, db_name: str = 'main', whitelist: Sequence = None, loop: asyncio.AbstractEventLoop = None, max_threads=3, client: TelegramClient = None): """ :param api_id: application ID :param api_hash: application hash :param bot_token: Bot Token obtained by @BotFather :param db_name: database name (default: 'main') :param whitelist: username whitelist :param loop: custom event loop :param client: custom TelegramClient instance, if provided, other parameters don't matter """ engine = create_engine('sqlite:///{}.db'.format(db_name)) self.session_cls = sessionmaker(bind=engine, class_=ImprovedSession) Base.metadata.create_all(bind=engine) self.logger = logging.getLogger('telegram-youtube-dl.bot') self.loop = loop or asyncio.get_event_loop() self.youtube_manager = YoutubeManager(self.loop, max_threads) if whitelist is not None: whitelist = set(whitelist) if client is not None: client.whitelist = whitelist self.client = client self.client.parse_mode = 'html' self.loop = client.loop return with use_session(self.session_cls) as db_session: bot_session = db_session.query( Session.data).filter(Session.bot_token == bot_token).scalar() client = TelegramClient(StringSession(bot_session), api_id, api_hash, loop=loop).start(bot_token=bot_token) if bot_session is None: db_session.add( Session(bot_token, api_id, api_hash, client.session.save())) db_session.commit() client.whitelist = whitelist self.client = client self.client.parse_mode = 'html' async def start(self): async with self.client as client: Handler.add_handlers_to_bot(self) await client.disconnected @Handler.register(NewMessage(pattern=r'^/start$')) async def on_start(self, event: NewMessage.Event): chat_id = event.chat_id with use_session(self.session_cls) as db_session: exists = db_session.query( db_session.query(User).filter( User.chat_id == chat_id).exists()).scalar() if not exists: db_session.add(User(chat_id)) self.logger.debug( 'New user ({}) was inserted into db'.format(chat_id)) db_session.commit() await event.respond('Welcome to Youtube Downloader Bot!', buttons=Button.clear()) @Handler.register(NewMessage(func=lambda e: e.message.is_reply)) async def on_reply(self, event: NewMessage.Event): msg = await event.client.get_messages( event.chat_id, ids=event.message.reply_to_msg_id) if not msg.is_reply: return media_msg = await event.client.get_messages(event.chat_id, ids=msg.reply_to_msg_id) if media_msg.file is None: return title = msg.text.split('\n')[0] await event.client.edit_message(msg, '\n'.join([title, event.raw_text])) await event.client.delete_messages(event.chat_id, event.message) raise StopPropagation @Handler.register(NewMessage(pattern=r'^http')) async def on_url(self, event: NewMessage.Event): if self.youtube_manager.is_downloading(event.chat_id): self.logger.debug('Already downloading for {}'.format( event.chat_id)) await event.respond('Something already downloading. Please wait') return url: str = event.raw_text self.logger.debug('Url received: {}'.format(url)) target_message = await event.respond('Checking...') info = await self.youtube_manager.get_info(url) if info is None: self.logger.debug('Video was not found') await event.respond('Video was not found', buttons=Button.clear()) return download_id = random_string(16) with use_session(self.session_cls, autocommit=True) as db_session: download = Download(event.chat_id, download_id, url, info['title'], info['duration'], json.dumps(info['formats'])) db_session.insert_or_replace(download) self.logger.debug('Download object was created for {}'.format( info['title'][:30])) await event.client.delete_messages( event.chat_id, [event.message.id, target_message.id]) await event.respond( '<b>{}</b>\nChoose download type:'.format(info['title']), buttons=[ Button.inline( 'Video', data=f'type_{download_id}_{DownloadType.VIDEO.name}'), Button.inline( 'Audio (default)', data=f'type_{download_id}_{DownloadType.AUDIO_DEFAULT.name}' ), Button.inline( 'Audio (custom)', data=f'type_{download_id}_{DownloadType.AUDIO_CUSTOM.name}' ) ]) @Handler.register(CallbackQuery(pattern=rb'^type_')) async def on_download_type_picked(self, event: CallbackQuery.Event): download_type = '_'.join(event.data.decode().split('_')[2:]) self.logger.debug('Download type was picked: {}'.format(download_type)) await event.delete() if download_type == DownloadType.VIDEO.name: return await self.on_type_video_picked(event) elif download_type == DownloadType.AUDIO_DEFAULT.name: return await self.on_type_audio_default_picked(event) elif download_type == DownloadType.AUDIO_CUSTOM.name: return await self.on_type_audio_custom_picked(event) self.logger.error( 'Invalid type was received: {}'.format(download_type)) async def on_type_video_picked(self, event: CallbackQuery.Event): download_id = event.data.decode().split('_')[1] with use_session(self.session_cls) as db_session: download = db_session.query(Download).filter( Download.chat_id == event.chat_id).one_or_none() if download is None or download.download_id != download_id: self.logger.error('Download object was not exists. Skip.') await event.delete() return formats = sorted(json.loads(download.video_format_list).items(), key=lambda x: int(x[0][:-1])) # matrix generation buttons = [[ Button.inline('{} ({} Mb)'.format( key, round(value['filesize'] / 1000000, 1)), data='video_{}_{}'.format(download_id, value['format_id'])) for key, value in formats[i * 3:(i + 1) * 3] ] for i in range(ceil(len(formats) / 3))] await event.respond( '<b>{}</b>\nChoose quality (if less then 10 Mb, GIF will be sent): ' .format(download.title), buttons=buttons) async def on_type_audio_default_picked(self, event: NewMessage.Event): pass async def on_type_audio_custom_picked(self, event: NewMessage.Event): pass @Handler.register(CallbackQuery(pattern=rb'^video_')) async def on_video_format_picked(self, event: CallbackQuery.Event): splitted_data = event.data.decode().split('_') download_id = splitted_data[1] format_id = '_'.join(splitted_data[2:]) self.logger.debug('Video format id was picked: {}'.format(format_id)) with use_session(self.session_cls) as db_session: download = db_session.query(Download).filter( Download.chat_id == event.chat_id).one_or_none() if download is None or download.download_id != download_id: self.logger.error('Download object was not exists. Skip.') await event.delete() return await event.delete() self.logger.debug('Start downloading {}'.format(download.url)) target_message = await event.respond( '<b>{}</b>\nStart downloading. Please wait'.format(download.title), buttons=Button.clear()) video_path = await self.youtube_manager.download_video( download.url, format_id, chat_id=event.chat_id) await event.client.delete_messages(event.chat_id, target_message) if video_path is None: self.logger.error('Cannot download. Error occurred') await event.respond( '<b>{}</b>\nCannot download. Something wrong'.format( download.title)) return self.logger.debug('Successfully downloaded. Start sending') target_message = await event.respond( '<b>{}</b>\nSuccessfully downloaded. Start sending'.format( download.title)) video_message = await event.client.send_file(event.chat_id, video_path) await event.client.delete_messages(event.chat_id, target_message) if Path(video_path).exists(): Path(video_path).unlink() self.logger.debug('Successfully sent') await event.respond('<b>{}</b>\n0:00'.format(download.title), reply_to=video_message)
from telethon import Button, events from telethon.events import NewMessage, StopPropagation from . import bot, botStartTime, logger, plugins, OWNER_ID from .utils import translate, fetch from .utils.bot_utils import get_readable_file_size, get_readable_time plugins.load() inline_search_buttons = [[ Button.switch_inline(translate.SEARCH_TRACK, same_peer=True), Button.switch_inline(translate.SEARCH_ALBUM, query=".a ", same_peer=True) ], [Button.inline('❌')]] @bot.on(NewMessage(pattern='/start')) async def start(event: NewMessage.Event): await event.reply(translate.WELCOME_MSG, buttons=inline_search_buttons) raise StopPropagation @bot.on(NewMessage(pattern='/help')) async def get_help(event: NewMessage.Event): await event.reply(translate.HELP_MSG) @bot.on(NewMessage(pattern='/info')) async def info(event: NewMessage.Event): await event.reply(translate.INFO_MSG) raise StopPropagation
onstate = states.StateHandler(db) withi18n = i18n.I18nHandler(db) logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) config = configparser.ConfigParser() config.read(args.config) bot = TelegramClient( str(Path(args.dbpath) / 'bot.session'), config['api']['id'], config['api']['hash']).start(bot_token=config['bot']['token']) @bot.on(NewMessage(pattern='/start')) @withi18n async def start_command_handler(event: NewMessage.Event, _): if not event.is_private: return await event.respond( _('Hi! To /find in your channel, you must /add it to this bot first.')) chat = await event.get_chat() db.save_user(chat) db.conn.commit() raise StopPropagation @bot.on(NewMessage(pattern='/add')) @onstate(states.Empty) @withi18n
async def start(e: NewMessage.Event): uid = e.sender.id text = e.message.text if text == "/start" or text == "بازگشت به منوی اصلی": try: u = User.select().where(User.uid == uid).get() except peewee.DoesNotExist: print("new user") u = User.create(uid=uid, status="", donated=0) u.save() await e.reply("Hello :)😆", buttons=KEYB) else: await e.reply("Welcome Back:)", buttons=KEYB) @client.on(NewMessage(from_users=ADMINS)) async def admin(e: NewMessage.Event): text = e.message.text uid = e.sender.id cid = e.chat_id if text == "test": print("test") for i in User.select(): print(i.uid, i.status, i.donated) for i in Phone.select(): print(i.number, i.donater, i.date, i.aid, i.ahsh, i.session) elif text == "/panel": await e.reply("Select :", buttons=client.build_reply_markup([[b("backup")], [b("member")]])) elif text == "backup":
import io from asyncio import gather from telethon.events import register, NewMessage from telethon.tl.custom import Message from utils.code_runners import CodeRunners commands = [ '.ex <code> - execute python code, event and client objects will be passed' ] @register(NewMessage(outgoing=True, pattern=r'(\.ex\s).+')) async def run_exec(event: Message): cmd = event.pattern_match.group(1) code: str = event.raw_text code = code.replace(cmd, '', 1) output = await CodeRunners.execute(code, event, event.client) output = CodeRunners.format_run(code, output) if len(output) > 4096: output = output.replace('\n', '<br>') with io.BytesIO() as file: file.name = 'exec.html' file.write(output.encode()) file.seek(0) await gather(event.delete(), event.respond(file=file)) else:
import logging from telethon.events import NewMessage, register from core.misc import controller, handlers from modules.nailerine.spoiling import utils_async log = logging.getLogger(__name__) flood = controller.anti_flood @register(NewMessage(outgoing=True, pattern=r'(?i)spoil member_ids')) async def spoil_member_ids(event: NewMessage.Event): await utils_async.do_spoil(event) @register(NewMessage(incoming=True, pattern=r'(?i)spoil member_ids')) @flood async def spoil_member_ids_public(event: NewMessage.Event): log.warning('%s requested members spoiler in %s', event.sender_id, event.chat) await utils_async.do_spoil(event) handlers.extend((spoil_member_ids, spoil_member_ids_public))
total_length = max(total_length, downloaded) current_message = await progress( downloaded, total_length, event, start, f"**Downloading({file_name}) from URL**") if current_message not in [display_message, "empty"]: await event.edit(current_message, parse_mode="html") display_message = current_message except Exception as e: print("Error", e) # logger.info(str(e)) return await response.release() @client.on(NewMessage()) async def upload(event): if event.media is None: return mesaj = await event.reply("`Your file downloading! Please Wait...`") baslangic = time.time() # if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY): # os.makedirs(TMP_DOWNLOAD_DIRECTORY) 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"))) x = await mesaj.edit("`Uploading to YaDisk! Please Wait...`") try: await Yandex.upload(filename, filename)