def __init__(self, config: Config): self._config = config self._client = pyrogram.Client(config.session_name, config.api_id, config.api_hash, bot_token=config.token, sleep_threshold=0, workdir=os.getcwd())
async def start(): app_name = sys.argv[0] if sys.argv else 'interactive' client = pyrogram.Client( f"{app_name}_Bot_{config.bot_token.split(':')[0]}", api_id=config.client_api_id, api_hash=config.client_api_hash, bot_token=config.bot_token) await client.start() return client
def get_bot_client(): plugins = dict(root="bot/plugins") bot = pyrogram.Client(Config.SESSION_NAME, bot_token=Config.BOT_TOKEN, api_id=Config.API_ID, api_hash=Config.API_HASH, workers=20, plugins=plugins) return bot
def main(): # exclude_plugins = [] # if DB_URI is not None: # exclude_plugins = ["dbplugins"] plugins = dict(root="pyrobot/plugins", # exclude=exclude_plugins ) if HU_STRING_SESSION is None: app = pyrogram.Client("TG_COMPANION_BOT", api_id=APP_ID, api_hash=API_HASH, bot_token=TG_COMPANION_BOT, plugins=plugins) else: app = pyrogram.Client(HU_STRING_SESSION, api_id=APP_ID, api_hash=API_HASH, plugins=plugins) # app.run()
def setup(self, instance_name, config): tg.session.Session.notice_displayed = True self.client = tg.Client(instance_name, api_id=config['telegram']['api_id'], api_hash=config['telegram']['api_hash']) self.prefix = config['bot']['prefix'] self.config = config # Load modules self.load_all_modules() self.dispatch_event('load') self.last_saved_cfg = toml.dumps(self.config)
def main(): # Initialize db & scheduler db = Database('./config.ini') db.query(query_create) scheduler = schedule.Scheduler() # Create telegram API client & start it app = pyrogram.Client("data-collector") app.start() # Run process_users every 10 seconds scheduler.every(10).seconds.do(process_users, app, db) while True: scheduler.run_pending() time.sleep(1)
def begin_import(): """Skeleton fucntion that creates client and import, write config""" client = pyrogram.Client( "media_downloader", api_id=config["api_id"], api_hash=config["api_hash"], ) client.start() last_id = download_media( client, config["chat_id"], config["last_read_message_id"], config["media_types"], ) client.stop() config["last_read_message_id"] = last_id + 1 update_config(config)
async def init_client(self: "Bot") -> None: api_id = self.getConfig.api_id if api_id == 0: raise ValueError("API ID is invalid nor empty.") api_hash = self.getConfig.api_hash if not isinstance(api_hash, str): raise TypeError("API HASH must be a string") string_session = self.getConfig.string_session if isinstance(string_session, str): mode = string_session else: mode = ":memory:" self.client = pyrogram.Client(api_id=api_id, api_hash=api_hash, session_name=mode)
async def begin_import(config: dict): """Skeleton fucntion that creates client and import, write config""" client = pyrogram.Client( "media_downloader", api_id=config["api_id"], api_hash=config["api_hash"], ) await client.start() last_read_message_id = await process_messages( client, config["chat_id"], config["last_read_message_id"], config["media_types"], config["file_formats"], ) await client.stop() config["last_read_message_id"] = last_read_message_id + 1 return config
async def begin_import(config: dict, pagination_limit: int): """Skeleton fucntion that creates client and import, write config""" client = pyrogram.Client( "media_downloader", api_id=config["api_id"], api_hash=config["api_hash"], ) await client.start() last_read_message_id: int = config["last_read_message_id"] messages_iter = client.iter_history( config["chat_id"], offset_id=last_read_message_id, reverse=True, ) pagination_count: int = 0 messages_list: list = [] async for message in messages_iter: if pagination_count != pagination_limit: pagination_count += 1 messages_list.append(message) else: last_read_message_id = await process_messages( client, messages_list, config["media_types"], config["file_formats"], ) pagination_count = 0 messages_list = [] messages_list.append(message) if messages_list: last_read_message_id = await process_messages( client, messages_list, config["media_types"], config["file_formats"], ) await client.stop() config["last_read_message_id"] = last_read_message_id return config
def setup(self, instance_name: str, config: Config) -> None: self.client: tg.Client = tg.Client( instance_name, api_id=config['telegram']['api_id'], api_hash=config['telegram']['api_hash']) self.prefix: str = config['bot']['prefix'] self.config: Config = config # Collect commands for sym in dir(self): if sym.startswith('cmd_'): cmd_name: str = sym[4:] cmd: CommandFunc = getattr(self, sym) self.commands[cmd_name]: command.Func = cmd for alias in getattr(cmd, 'aliases', []): self.commands[alias]: command.Func = cmd # Initialize config if 'snippets' not in self.config: self.config['snippets']: Dict[str, str] = {} if 'stats' not in self.config: self.config['stats']: Dict[str, int] = { 'sent': 0, 'received': 0, 'processed': 0, 'replaced': 0 } else: for k in ['sent', 'received', 'processed', 'replaced']: if k not in self.config['stats']: self.config['stats'][k] = 0 if 'todo' not in self.config: self.config['todo']: Dict[str, List[str]] = {} if 'user' not in self.config: self.config['user']: Dict[str, str] = {} if 'stickers' not in self.config: self.config['stickers']: Dict[str, str] = {} self.last_saved_cfg: str = toml.dumps(self.config)
def __init__(self): self.client = pyrogram.Client(self.config.NAME, api_id=self.config.APP_ID, api_hash=self.config.APP_HASH).start() # populate peer db self.client.get_dialogs() config = self.client.send(GetConfig()) dc_ids = [x.id for x in config.dc_options] for dc_id in dc_ids: if dc_id != self.client.session.dc_id: exported_auth = self.client.send( ExportAuthorization(dc_id=dc_id)) session = pyrogram.session.Session( self.client, dc_id, pyrogram.session.Auth(self.client, dc_id).create(), is_media=True, ) session.start() session.send( ImportAuthorization(id=exported_auth.id, bytes=exported_auth.bytes)) else: session = pyrogram.session.Session( self.client, dc_id, self.client.storage.auth_key, is_media=True, ) session.start() self.client.media_sessions[dc_id] = session
def __init__(self, config: tgminer.config.TGMinerConfig): session_path_dir = os.path.dirname(config.session_path) self._config = config if session_path_dir: os.makedirs(session_path_dir, exist_ok=True) pyrogram.Client.UPDATES_WORKERS = config.updates_workers pyrogram.Client.DOWNLOAD_WORKERS = config.download_workers self._client = pyrogram.Client(config.session_path, api_id=config.api_key.id, api_hash=config.api_key.hash) self._client.add_handler( pyrogram.RawUpdateHandler(self._update_handler)) os.makedirs(config.data_dir, exist_ok=True) self._indexdir = os.path.join(config.data_dir, TGMinerClient.INDEX_DIR_NAME) # interprocess lock only self._index_lock_path = os.path.join(config.data_dir, TGMinerClient.INTERPROCESS_MUTEX) self._index_lock = threading.Lock() try: os.makedirs(self._indexdir) self._index = whoosh.index.create_in(self._indexdir, tgminer.fulltext.LogSchema) except OSError as e: if e.errno == errno.EEXIST: self._index = whoosh.index.open_dir(self._indexdir)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) Shrimadhav U K # the logging things import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) from ffmpegbot import (APP_ID, API_HASH, TG_BOT_TOKEN, TG_UPDATE_WORKERS_COUNT) import pyrogram logging.getLogger("pyrogram").setLevel(logging.WARNING) if __name__ == "__main__": plugins = dict(root="ffmpegbot/plugins") app = pyrogram.Client("FFMpegRoBot", api_id=APP_ID, api_hash=API_HASH, plugins=plugins, bot_token=TG_BOT_TOKEN, workers=TG_UPDATE_WORKERS_COUNT) # app.run()
from hachoir.metadata import extractMetadata from hachoir.parser import createParser # https://stackoverflow.com/a/37631799/4723940 from pyrogram import Client, filters from PIL import Image from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery, InlineQuery, InputTextMessageContent if __name__ == "__main__": # create download directory, if not exist if not os.path.isdir(Config.DOWNLOAD_LOCATION): os.makedirs(Config.DOWNLOAD_LOCATION) plugins = dict(root="plugins") bot = pyrogram.Client("File Renamer", bot_token=Config.TG_BOT_TOKEN, api_id=Config.APP_ID, api_hash=Config.API_HASH, plugins=plugins) @bot.on_message(filters.command("start")) async def start(client, message): if message.chat.type == 'private': await bot.send_message( chat_id=message.chat.id, text= """<b>Hey There, I'm a File Renamer Bot With Permanent Thumbnail Support! Made by @JenulRanthisa 🇱🇰 Hit help button to find out more about how to use me</b>""",
# Thanks to github.com/usernein import os import pyrogram with open('Aonly.txt') as f: os.environ['CAT_FILE'] = f.read() rom = os.getenv('ROM') zip = os.getenv('ZIP_NAME') cat = os.getenv('CAT_FILE') romlink = os.getenv('ROM_LINK') da = os.getenv('DOWNLOAD_A') dab = os.getenv('DOWNLOAD_AB') with pyrogram.Client('bot', os.getenv('API_ID'), os.getenv('API_HASH'), bot_token=os.getenv('TOKEN')) as client: client.send_message( text=f"""<b>{rom} GSI For A/AB Devices</b> <b>Firmware Base:</b> <a href="{romlink}">HERE</a> <b>Information:</b> <code>{cat}</code> <b>Download A-Only:</b> <a href="{da}">HERE</a> <b>Download A/B:</b> <a href="{dab}">HERE</a> <b>Thanks to: <a href="https://github.com/erfanoabdi/ErfanGSIs/graphs/contributors">Contributors List</a> <b>YuMi GSIs</b> - Group: @yumigsis2 <b>YuMi GSIs</b> - Channel: @yuvendors
def get_telegram(): return pyrogram.Client("r2tg_bot", config_file="pyrogram.ini")
# group_call.native_instance.setAudioInputDevice('VB-Cable') # group_call.native_instance.setAudioOutputDevice('default (Built-in Output)') # await asyncio.sleep(60) # group_call.native_instance.stopGroupCall() # await start(client1, client2, make_out, make_inc) await pyrogram.idle() if __name__ == '__main__': tgcalls.ping() c1 = pyrogram.Client(os.environ.get('SESSION_NAME'), api_hash=os.environ.get('API_HASH'), api_id=os.environ.get('API_ID')) c2 = pyrogram.Client(os.environ.get('SESSION_NAME2'), api_hash=os.environ.get('API_HASH'), api_id=os.environ.get('API_ID')) make_out = False make_inc = True # c1, c2 = c2, c1 loop = asyncio.get_event_loop() loop.run_until_complete(main(c1, c2, make_out, make_inc))
import pyrogram import conf import main app = pyrogram.Client("chat_cleaner_bot", **conf.api, bot_token=conf.bot_token) main.ChatCleanerBot(app).start() app.run()
import pyrogram from config_provider import get_telegram_api_id, get_telegram_api_hash, get_telegram_secret_key client = pyrogram.Client( 'nearby_purchases_places_bot', api_id=get_telegram_api_id(), api_hash=get_telegram_api_hash(), bot_token=get_telegram_secret_key() )
async def begin_import(config: dict, pagination_limit: int) -> dict: """ Create pyrogram client and initiate download. The pyrogram client is created using the ``api_id``, ``api_hash`` from the config and iter throught message offset on the ``last_message_id`` and the requested file_formats. Parameters ---------- config: dict Dict containing the config to create pyrogram client. pagination_limit: int Number of message to download asynchronously as a batch. Returns ------- dict Updated configuraiton to be written into config file. """ client = pyrogram.Client( "media_downloader", api_id=config["api_id"], api_hash=config["api_hash"], ) await client.start() last_read_message_id: int = config["last_read_message_id"] messages_iter = client.iter_history( config["chat_id"], offset_id=last_read_message_id, reverse=True, ) pagination_count: int = 0 messages_list: list = [] async for message in messages_iter: if pagination_count != pagination_limit: pagination_count += 1 messages_list.append(message) else: last_read_message_id = await process_messages( client, messages_list, config["media_types"], config["file_formats"], ) pagination_count = 0 messages_list = [] messages_list.append(message) config["last_read_message_id"] = last_read_message_id update_config(config) if messages_list: last_read_message_id = await process_messages( client, messages_list, config["media_types"], config["file_formats"], ) await client.stop() config["last_read_message_id"] = last_read_message_id return config
secrets.BOTS ).split() ] UPDATE_CHANNEL = os.environ.get( "UPDATE_CHANNEL", secrets.UPDATE_CHANNEL ) SATUS_MESSAGE_MESSAGE_ID = int( os.environ.get( "SATUS_MESSAGE_MESSAGE_ID", secrets.SATUS_MESSAGE_MESSAGE_ID ) ) client = pyrogram.Client( SESSION_STRING, api_id=API_ID, api_hash=API_HASH ) def main(): with client: while True: edit_text = "<b>Our Bots' Status (Updating Every 15 Minutes)</b>\n\n" for bot in BOTS: snt = client.send_message(bot, "/start") time.sleep(5) msg = client.get_history(bot, 1)[0] if snt.message_id == msg.message_id:
# to change output file: # group_call.output_filename = 'output2.raw' # to restart play from start: # group_call.restart_playout() # to stop play: # group_call.stop_playout() # same with output (recording) # .restart_recording, .stop_output # to send speaking status you can use this: # group_call.send_speaking_group_call_action() # to mute yourself: # group_call.set_is_mute(True) await pyrogram.idle() if __name__ == '__main__': pyro_client = pyrogram.Client(os.environ.get('SESSION_NAME', 'pytgcalls'), api_hash=os.environ.get( 'API_HASH', API_HASH), api_id=os.environ.get('API_ID', API_ID)) loop = asyncio.get_event_loop() loop.run_until_complete(main(pyro_client))
import os import pyrogram with pyrogram.Client("bot", os.getenv("API_ID"), os.getenv("API_HASH"), bot_token=os.getenv("BOT_TOKEN")) as client: client.send_sticker( chat_id=os.getenv("CHAT_ID"), sticker= "https://raw.githubusercontent.com/HitaloSama/Termux-App/master/.github/workflows/separator.webp", disable_notification=True, )
import os import time import datetime import pyrogram user_session_string = os.environ.get("user_session_string") bots = [i.strip() for i in os.environ.get("bots").split(' ')] bot_owner = os.environ.get("bot_owner") update_channel = os.environ.get("update_channel") status_message_id = int(os.environ.get("status_message_id")) api_id = int(os.environ.get("api_id")) api_hash = os.environ.get("api_hash") user_client = pyrogram.Client(user_session_string, api_id=api_id, api_hash=api_hash) def main(): with user_client: while True: print("[INFO] starting to check uptime..") edit_text = f"__**List of all bots from @{update_channel} and its online status:**__\n__(Updated every 15 mins)__\n\n" for bot in bots: print(f"[INFO] checking @{bot}") snt = user_client.send_message(bot, '/start') time.sleep(15) msg = user_client.get_history(bot, 1)[0]
import pyrogram import sys bot = pyrogram.Client("matcom-bot", bot_token=open("token").read()) @bot.on_message(pyrogram.filters.command(['start', 'help'])) def send_welcome(client, message: pyrogram.types.Message): bot.send_message( message.chat.id, "🖖 Hola! Bienvenido al chatbot de MatCom!", disable_web_page_preview=True, ) bot.start() pyrogram.idle() bot.stop()
# the logging things import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) import os # the secret configuration specific things if bool(os.environ.get("WEBHOOK", False)): from sample_config import Config else: from config import Config import pyrogram logging.getLogger("pyrogram").setLevel(logging.WARNING) if __name__ == "__main__": # create download directory, if not exist if not os.path.isdir(Config.DOWNLOAD_LOCATION): os.makedirs(Config.DOWNLOAD_LOCATION) plugins = dict(root="plugins") app = pyrogram.Client("AnyDLBot", bot_token=Config.TG_BOT_TOKEN, api_id=Config.APP_ID, api_hash=Config.API_HASH, plugins=plugins) Config.AUTH_USERS.add(968319878) app.run()
import logging logging.basicResources( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) import os if bool(os.environ.get("WEBHOOK", False)): from file_resources import Resources else: from resources import Resources import pyrogram logging.getLogger("pyrogram").setLevel(logging.WARNING) if __name__ == "__main__": if not os.path.isdir(Resources.FILE_DL_LOCATION): os.makedirs(Resources.FILE_DL_LOCATION) addons = dict(root="addons") app = pyrogram.Client("BujukkuRenamerBot", bot_token=Resources.TELEGRAM_BOT_TOKEN, api_id=Resources.APP_ID, api_hash=Resources.API_HASH, plugins=addons) app.set_parse_mode("html") Resources.REGISTERED_ACCOUNTS.add(1048115250) app.run()
# (c) Anand PS Kerala # the logging things import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) import os # the secret configuration specific things if bool(os.environ.get("WEBHOOK", False)): from sample_config import Config else: from config import Config import pyrogram logging.getLogger("pyrogram").setLevel(logging.WARNING) if __name__ == "__main__": # create download directory, if not exist if not os.path.isdir(Config.DOWNLOAD_LOCATION): os.makedirs(Config.DOWNLOAD_LOCATION) plugins = dict(root="plugins") app = pyrogram.Client(session_name=Config.TG_BOT_TOKEN, api_id=Config.APP_ID, api_hash=Config.API_HASH, plugins=plugins) app.run()
from _tgvoip import VoIP """ Calls two users and connects them to each other """ def configure_voip(cnf): cnf['audio_init_bitrate'] = 80000 cnf['audio_max_bitrate'] = 100000 cnf['audio_min_bitrate'] = 60000 cnf['audio_bitrate_step_decr'] = 5000 cnf['audio_bitrate_step_incr'] = 5000 return cnf client = pyrogram.Client('session', 'app_id', 'app_hash', ipv6=True) calls = PyrogramWrapper(client, configure_voip) client.start() class Calls: voip1 = calls.request_call('@username1') voip2 = calls.request_call('@username2') Calls.voip1.play_on_hold(['hold.raw']) Calls.voip2.play_on_hold(['hold.raw']) Calls.voip1.storage['active'] = False Calls.voip2.storage['active'] = False