def get_cached_client(): """Gets an authorized TelegramClient, performing the authorization process if it's the first time""" global cached_client if not cached_client: print('Loading client...') settings = load_settings() cached_client = TelegramClient(session_user_id=settings.get('session_name', 'anonymous'), api_id=settings['api_id'], api_hash=settings['api_hash']) cached_client.connect() # Then, ensure we're authorized and have access if not cached_client.is_user_authorized(): # Import the login window locally to avoid cyclic dependencies from gui.windows import LoginWindow print('First run, client not authorized. Sending code request.') cached_client.send_code_request(str(settings['user_phone'])) start_app(LoginWindow, client=cached_client, phone=settings['user_phone']) del LoginWindow print('Client loaded and authorized.') return cached_client
def main(): session_name = environ.get('TG_SESSION', 'session') client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], proxy=None, update_workers=4, spawn_read_thread=False) if 'TG_PHONE' in environ: client.start(phone=environ['TG_PHONE']) else: client.start() client.add_event_handler(update_handler) print('(Press Ctrl+C to stop this)') client.idle()
def __init__(self): config = configparser.ConfigParser() config.read('../conf/config.ini') api_id = config['TELEGRAM']['api_id'] api_hash = config['TELEGRAM']['api_hash'] print(api_id,' ',api_hash) self.telegram = TelegramClient("BitCoinDev", api_id, api_hash) self.telegram.connect() if not self.telegram.is_user_authorized(): self.telegram.send_code_request('+821097950344') self.telegram.sign_in('+821097950344', input('Enter the code: '))
while True: value = input(message) try: return cast(value) except ValueError as e: print(e, file=sys.stderr) time.sleep(1) session = os.environ.get('TG_SESSION', 'printer') api_id = get_env('TG_API_ID', 'Enter your API ID: ', int) api_hash = get_env('TG_API_HASH', 'Enter your API hash: ') proxy = None # https://github.com/Anorov/PySocks # Create and start the client so we can make requests (we don't here) client = TelegramClient(session, api_id, api_hash, proxy=proxy).start() # `pattern` is a regex, see https://docs.python.org/3/library/re.html # Use https://regexone.com/ if you want a more interactive way of learning. # # "(?i)" makes it case-insensitive, and | separates "options". @client.on(events.NewMessage(pattern=r'(?i).*\b(hello|hi)\b')) async def handler(event): sender = await event.get_sender() name = utils.get_display_name(sender) print(name, 'said', event.text, '!') try: print('(Press Ctrl+C to stop this)') client.run_until_disconnected()
logging.debug('dbg') logging.info('info') """ REACTS = {'emacs': 'Needs more vim', 'chrome': 'Needs more Firefox'} # A list of dates of reactions we've sent, so we can keep track of floods recent_reacts = defaultdict(list) if __name__ == '__main__': # TG_API_ID and TG_API_HASH *must* exist or this won't run! session_name = environ.get('TG_SESSION', 'session') client = TelegramClient( session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], spawn_read_thread=False, proxy=None, update_workers=4 ) @client.on(events.NewMessage) def my_handler(event: events.NewMessage.Event): global recent_reacts # This utils function gets the unique identifier from peers (to_id) to_id = utils.get_peer_id(event.message.to_id) # Through event.raw_text we access the text of messages without format words = re.split('\W+', event.raw_text) # Try to match some reaction for trigger, response in REACTS.items(): if len(recent_reacts[to_id]) > 3:
def __init__(self): config = configparser.ConfigParser() config.read('config.ini') api_id = config.get('telegram_api', 'api_id') api_hash = config.get('telegram_api', 'api_hash') workers = config.get('telegram_api', 'workers') session_name = config.get('telegram_api', 'session_name') self.timezone = int(config.get('other', 'timezone')) self.message_dialog_len = int(config.get('app', 'message_dialog_len')) # proxy settings if config.get('proxy', 'type') == "HTTP": proxy_type = socks.HTTP elif config.get('proxy', 'type') == "SOCKS4": proxy_type = socks.SOCKS4 elif config.get('proxy', 'type') == "SOCKS5": proxy_type = socks.SOCKS5 else: proxy_type = None proxy_addr = config.get('proxy', 'addr') proxy_port = int(config.get('proxy', 'port')) if config.get('proxy', 'port').isdigit() else None proxy_username = config.get('proxy', 'username') proxy_password = config.get('proxy', 'password') proxy = (proxy_type, proxy_addr, proxy_port, False, proxy_username, proxy_password) # create connection self.client = TelegramClient(session_name, api_id, api_hash, update_workers=int(workers), spawn_read_thread=True, proxy=proxy) self.client.start() self.me = self.client.get_me() self.dialogs = self.client.get_dialogs(limit=self.message_dialog_len) self.messages = len(self.dialogs) * [None] self.online = len(self.dialogs) * [""] self.messages[0] = self.client.get_message_history(self.dialogs[0].entity, limit=self.message_dialog_len) # event for new messages @self.client.on(events.NewMessage) def my_event_handler(event): for i in range(len(self.dialogs)): # if event message from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event._chat_peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event._chat_peer.chat_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'channel_id') and hasattr(event._chat_peer, 'channel_id') and \ self.dialogs[i].dialog.peer.channel_id == event._chat_peer.channel_id: self.event_message(i) # other else: pass # event for read messages @self.client.on(events.Raw(types=None)) def my_event_handler(event): if hasattr(event, 'confirm_received') and hasattr(event, 'max_id'): for i in range(len(self.dialogs)): # from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event.peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event.peer.user_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event.peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event.peer.chat_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # other else: pass self.need_update_read_messages = 1 # event for online/offline @self.client.on(events.UserUpdate(chats=None, blacklist_chats=False)) def my_event_handler(event): for i in range(len(self.dialogs)): if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: # I think need little bit change this if event.online: self.online[i] = "Online" elif event.last_seen is not None: self.online[i] = "Last seen at " + str(event.last_seen + (timedelta(self.timezone) // 24)) else: self.online[i] = "" self.need_update_current_user = i self.need_update_online = 1
async def add_bot(bot_token): await bot.start(bot_token) bot.me = await bot.get_me() bot.uid = telethon.utils.get_peer_id(bot.me) if len(argv) not in (1, 3, 4): bot.disconnect() else: bot.tgbot = None if Var.TG_BOT_USER_NAME_BF_HER is not None: print(" Initiating Inline Bot ") # ForTheGreatrerGood of beautification bot.tgbot = TelegramClient( "TG_BOT_TOKEN", api_id=Var.APP_ID, api_hash=Var.API_HASH).start(bot_token=Var.TG_BOT_TOKEN_BF_HER) print( "Initialisation finished with no errors , Your 🔱╚»★𝐑𝐃𝐗 bot★«╝🔱 will be ready in sometime" ) print("Starting 🔱╚»★𝐑𝐃𝐗 bot★«╝🔱") bot.loop.run_until_complete(add_bot(Var.TG_BOT_USER_NAME_BF_HER)) print("🔱╚»★𝐑𝐃𝐗 bot★«╝🔱's Startup Completed") else: bot.start() import glob path = "userbot/plugins/*.py" files = glob.glob(path) for name in files:
class TelegramClientObj(object): def __init__(self, telegram_setting = None, message_handler_callback = None): try: self.message_handler_callback = message_handler_callback self.user_master_id = telegram_setting['USER_ID_MASTER'] self.telegram_cli = TelegramClient( telegram_setting['SESSION'], telegram_setting['ID'], telegram_setting['HASH'], update_workers=1, spawn_read_thread=False) self.telegram_cli.add_event_handler(self.new_message_handler, events.NewMessage) self.telegram_cli.start() self.initialize = True logger.debug("TelegramClient initialize") except Exception as err: pass self.initialize = False self.telegram_cli = None logger.error("TelegramClient fail %s" % (Utility.get_error_msg(),)) def new_message_handler(self, event): try: logger.debug(event) if self.message_handler_callback is not None: self.message_handler_callback(self, event) except Exception as err: pass logger.error(Utility.get_error_msg()) def reply_message(self, to=None, msg=None): try: self.telegram_cli.send_message("me", msg) # self.telegram_cli.send_message(self.user_master_id, msg) if to is not None: self.telegram_cli.send_message(to, msg) except Exception as err: pass logger.error(Utility.get_error_msg()) def reply_file(self, to=None, filex=None): try: self.telegram_cli.send_file("me", filex) # self.telegram_cli.send_file(self.user_master_id, filex) if to is not None: self.telegram_cli.send_file(to, filex) except Exception as err: pass logger.error(Utility.get_error_msg()) def start_loop(self): try: self.telegram_cli.idle() except Exception as err: pass logger.error(Utility.get_error_msg())
StockPreisVKList = {} StockAnzahlList = {} if BlueLoad("Telegram", "DATA/DATA") == "1": Telegram = True try: from telethon import TelegramClient, utils except: import os print("Module Telethon, not installed, starting Installation...") os.system("pip3 install --user telethon") print("Module Telethon Installed, please restart APP...") api_id = 291651 api_hash = '0f734eda64f8fa7dea8ed9558fd447e9' client = TelegramClient('telepygram', api_id, api_hash) isConnected = client.connect() # return True print("Connection: " + str(isConnected)) isAuthorized = client.is_user_authorized() print("Authorized: " + str(isAuthorized)) if not isAuthorized: phone_number = input( "Enter your phone number\nIn international format please\n") print("Phone is " + str(phone_number)) client.send_code_request(phone_number) authorized_code = input("Please enter code:\n") me = client.sign_in(phone_number, authorized_code) TelegramContact = BlueLoad("TelegramContact", "DATA/DATA") client.send_message(TelegramContact, "Server gestarted")
class TGMemExtrator(object): def __init__(self, config): self.session_name = config['TG_session_name'] self.api_id = config['TG_api_id'] self.api_hash = config['TG_api_hash'] self.proxy_address = config['proxy_address'] self.proxy_port = config['proxy_port'] self.group_username = '' self.member_path = config['group_member'] self.group_avatar_path = config['group_avatar'] self.client = TelegramClient(self.session_name, self.api_id, self.api_hash, proxy=(socks.HTTP, self.proxy_address, self.proxy_port)) # 设置需要采集的telegram group username def set_channel(self, username): self.group_username = username # 换账号连接 def TG_login(self, config): session = config['TG_session_name'] api_id = config['TG_api_id'] api_hash = config['TG_api_hash'] proxy_address = config['proxy_address'] proxy_port = config['proxy_port'] self.client = TelegramClient(session, api_id, api_hash, proxy=(socks.HTTP, proxy_address, proxy_port)) # 指定user,下载头像 async def download_profile_pic(self, username): # 根据username获取group的实体 try: chat_item = await self.client.get_entity(username) except ValueError: print("ValueError:No group has\"", self.group_username, "\"as username") return None # 下载图片 other = self.group_avatar_path + "\other" os.makedirs(other) if chat_item.photo is not None: data = await self.client.download_profile_photo(chat_item, file=other) else: data = None return data # 将采集的User信息转换成系统自定义的实体类处理 def UserToMemberEntity(self, user, pic_addr, admins): # 提取username,name member = memberEntity.memberEnitity() member.initWithUser(user) for i in range(admins.__len__()): if admins[i] == id: member.set_adminInfo(True) member.set_ProfilePic(pic_addr) return member # 获取群管理员的id async def get_group_administrator(self): admin_ids = [] # 根据username获取group的实体 try: chat_item = await self.client.get_entity(self.group_username) except ValueError: print("ValueError:No group has\"", self.group_username, "\"as username") return admin_ids # 判断实体为channel返回空数据,实体为user返回空数据,实体为group继续执行下面代码 if isinstance(chat_item, Channel): if chat_item.megagroup is False: print( "ValueError:its a channel ,cant get chaneel members without admin privileges" ) return admin_ids else: print("ValueError:its a User ,cant get a User's members") return admin_ids # 获取group的管理员 admins = self.client.iter_participants( chat_item, filter=ChannelParticipantsAdmins) i = 0 admin_ids = [] async for admin in admins: admin_ids.append(admin.id) i += 1 return admin_ids # 获取telegram group member 接口 async def get_group_member(self, Download_pic_flag): # 根据username获取group的实体 try: chat_item = await self.client.get_entity(self.group_username) except ValueError: print("ValueError:No group has\"", self.group_username, "\"as username") return # 判断实体为channel返回空数据,实体为user返回空数据,实体为group继续执行下面代码 reslut = {"data": ""} memFilePath = self.member_path + chat_item.username + ".json" if isinstance(chat_item, Channel): if chat_item.megagroup is False: channel = channelEntity.channelEnitity() channel.initWithChannel(chat_item) channel.set_Member_Account(chat_item.participants_count) reslut["data"] = channel.__dict__ # 将最后结果写到指定文件下 with open(memFilePath, "w") as f: json.dump(reslut, f, sort_keys=True, indent=4, separators=(',', ':'), default=str) f.close() print( "ValueError:its a channel ,cant get chaneel members without admin privileges" ) return else: print("ValueError:its a User ,cant get a User's member") return # 获取group的全部成员 participants = await self.client.get_participants(chat_item, aggressive=True) # 获取group的管理员 admins = self.client.iter_participants( chat_item, filter=ChannelParticipantsAdmins) i = 0 admin_ids = [] async for admin in admins: admin_ids.append(admin.id) i += 1 # 获取群成员 path = (self.group_avatar_path + chat_item.username).strip() os.makedirs(path, exist_ok=True) group_avatar = await self.client.download_profile_photo(chat_item, file=path) group = groupEntity.groupEnitity() group.initWithGroup(chat_item) group.set_Member_Account(participants.total) if group_avatar: group.set_Avatar(self.group_avatar_path, group_avatar) for user in participants: # 下载图片 addr = None if Download_pic_flag: try: if user.photo is not None: addr = await self.client.download_profile_photo( user, file=path) print(addr) except ChannelInvalidError: print("download error") # 获取群成员信息 mem = self.UserToMemberEntity(user, addr, admin_ids) # if count >= 100: # count = 1 # reslut["data"]=group.__dict__ # # 将最后结果写到指定文件下 # with open(memFilePath, "a") as f: # json.dump(reslut, f, sort_keys=True, indent=4, separators=(',', ':'), default=str) # f.close() # group.add_Member(mem.__dict__,True) # continue # count += 1 group.add_Member(mem.__dict__) reslut["data"] = group.__dict__ # 将最后结果写到指定文件下 with open(memFilePath, "w") as f: json.dump(reslut, f, sort_keys=True, indent=4, separators=(',', ':'), default=str) f.close() print("get channel Member successfully") def dumpTojson(self, Download_pic_flag): with self.client: self.client.loop.run_until_complete( self.get_group_member(Download_pic_flag))
conn = create_connection_sql('bot.db') if debug == 'true': denominator = 2 else: denominator = 15 log.debug('Start event loop...') while True: current_minute = int(datetime.now().strftime('%M')) if (current_minute + 1) % denominator == 0 or current_minute % denominator == 0: client = TelegramClient( 'session_name', api_id, api_hash, connection=connection.ConnectionTcpMTProxyIntermediate, proxy=proxy) client.flood_sleep_threshold = 24 * 60 * 60 create_connection_tg(client) channel = client.get_entity(PeerChannel(int(channel_id))) if not client.is_user_authorized(): client.send_code_request(phone) try: client.sign_in(phone, input('Enter the code: ')) except SessionPasswordNeededError: client.sign_in(password=input('Password: '******'Parsing channel...') all_messages = []
import os import sys import time from telethon.sessions import StringSession from telethon import TelegramClient from userbot.helpers import functions as simpdef from userbot.Config import Config from var import Var StartTime = time.time() hellversion = "0.0.1" os.system("pip install --upgrade pip") if Var.STRING_SESSION: session_name = str(Var.STRING_SESSION) bot = TelegramClient(StringSession(session_name), Var.APP_ID, Var.API_HASH) else: session_name = "startup" bot = TelegramClient(session_name, Var.APP_ID, Var.API_HASH) CMD_LIST = {} # for later purposes CMD_HELP = {} CMD_HELP_BOT = {} BRAIN_CHECKER = [] INT_PLUG = "" LOAD_PLUG = {} # PaperPlaneExtended Support Vars ENV = os.environ.get("ENV", False)
# This file is part of lynda (Telegram Bot) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from telethon import TelegramClient from lynda.services.str_key import get_int_key, get_str_key TOKEN = get_str_key("TOKEN", required=True) NAME = TOKEN.split(":")[0] client = TelegramClient(NAME, get_int_key("API_ID", required=True), get_str_key("API_HASH", required=True)) # Telethon client.start(bot_token=TOKEN)
async def teleCreateSession(api_id: int, api_hash: str): return TelegramClient(StringSession(), api_id=int(api_id), api_hash=str(api_hash))
# ------------------------------------------- < Proxy Setup > ------------------------------------------- if conf.AUTHENTICATION: sockProxy = { "proxy_type": socks.SOCKS5, "addr": conf.SOCKS5_SERVER, "port": conf.SOCKS5_PORT, "rdns": True, "username": conf.USERNAME, "password": conf.PASSWORD } if conf.PROXY: if conf.AUTHENTICATION: if conf.USERNAME != None and conf.PASSWORD != None: client = TelegramClient('anon', api_id, api_hash, proxy=sockProxy) bot = TelegramClient('bot', api_id, api_hash, proxy=sockProxy) elif not conf.AUTHENTICATION: print(f'Using proxy server {conf.SOCKS5_SERVER}:{conf.SOCKS5_PORT}') client = TelegramClient('anon', api_id, api_hash, proxy=( socks.SOCKS5, conf.SOCKS5_SERVER, conf.SOCKS5_PORT)) bot = TelegramClient('bot', api_id, api_hash, proxy=( socks.SOCKS5, conf.SOCKS5_SERVER, conf.SOCKS5_PORT)) else: client = TelegramClient('anon', api_id, api_hash) # ------------------------------------------- < Helper Functions > ------------------------------------------- # Get the answer from user if sent a single answer poll async def guideRes(dict, list):
print(' ', msg[:75] + '...' if len(msg) > 78 else msg) # channel = client.get_entity('https://t.me/huytest') # print(channel.stringify()) # print(client.get_messages(channel, 5)) client.add_event_handler(print_message, events.NewMessage(chats=1332837514, incoming=True)) client.catch_up() print('event handlers:', client.list_event_handlers()) def stop(client): client.disconnect() if __name__ == "__main__": if len(sys.argv) < 2: print('Usage:', os.path.basename(__file__), '<phone_number>') exit(1) client = TelegramClient( os.path.abspath( config.get('paths', 'sessions') + '/' + parse_phone(sys.argv[1]) ), config.get('telegram', 'api_id'), config.get('telegram', 'api_hash') ) try: start(client) client.run_until_disconnected() finally: stop(client)
import pandas as pd from datetime import datetime, timedelta import time """ NOTES: 1. if get database locked error, that means havent closed session properly. Use client.log_out() 2. Go create app in Telegram to get below values """ api_hash = "" api_id= "" phonenumber = "" client = TelegramClient(phonenumber, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phonenumber) client.sign_in(phonenumber, input('Enter the code: ')) def xstr(s): if s is None: return '' return str(s) def chatstocsv(channel_username,filestodl=[]): if ":::?:::" in channel_username: channel_IDusername,channel_username = channel_username.split(":::?:::")
pid = 'coin.run' print('CryptoAlert Auto-Trader, with live updates...') print('CryptoAlert Auto-Trader, with live updates...') print('CryptoAlert Auto-Trader, with live updates...') print('CTRL-C To exit') print('CTRL-C To exit') print('CTRL-C To exit') print('To test me, type a coin into the cryptoping telegram bot window on telegram such as #LTC and #DASH') print('The Telegram updates in a while loop, and creates a pid equialent... delete coin.run if exiting in the middle of a sell signal') threads = [] flag = "test" variable = "test" api_id = 189914 api_hash = '75b1fbdede4c49f7b7ca4a8681d5dfdf' # 'session_id' can be 'your_name'. It'll be saved as your_name.session client = TelegramClient('session_id', api_id, api_hash) client.connect() # PUT YOUR PHONE NUMBER ASSICOATED WITH TELEGRAM BELOW google voice works... if not client.is_user_authorized(): client.send_code_request('+14698447320') client.sign_in('+14698447320', input('Enter code: ')) # Now you can use the connected client as you wish def generate_random_long(): import random return random.choice(range(0,10000000))
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s", datefmt='%d-%b-%y %H:%M:%S', handlers=[ RotatingFileHandler("GetSongsBot.log", maxBytes=50000000, backupCount=1), logging.StreamHandler() ]) def LOGGER(name: str) -> logging.Logger: """ get a Logger object """ return logging.getLogger(name) client = TelegramClient("MediaSearchBot", APP_ID, API_HASH).start(bot_token=TG_BOT_TOKEN) client.parse_mode = "html" user_client = TelegramClient(StringSession(TG_USER_SESSION), APP_ID, API_HASH).start() user_client.parse_mode = "html" async def search_tg(_u: TelegramClient, _b: TelegramClient, event: events.InlineQuery.Event, sqr: str, astr: int, lmtn: int): mtls = await _u.get_messages(entity=TG_DB_CHAT, limit=lmtn, offset_id=astr, search=sqr) t_r = mtls.total
dotenv_path = os.path.join(os.path.dirname(__file__), ".env") print((dotenv_path)) if os.path.exists(dotenv_path): load_dotenv(dotenv_path) app_api_id = os.getenv("TLG_APP_API_ID") app_api_hash = os.getenv("TLG_APP_API_HASH") app_name = os.getenv("TLG_APP_NAME") bot_token = os.getenv("I_BOT_TOKEN") client = os.getenv("TLG_CLIENT") proxy_server = os.getenv("TLG_PROXY_SERVER") proxy_port = int(os.getenv("TLG_PROXY_PORT")) proxy_key = os.getenv("TLG_PROXY_KEY") proxy = (proxy_server, proxy_port, proxy_key) bot = TelegramClient(app_name, app_api_id, app_api_hash, connection=connection.ConnectionTcpMTProxyRandomizedIntermediate, proxy=proxy) bot.start(bot_token=bot_token) # client = [] # клиент @bot.on(events.NewMessage(pattern='/start')) async def start(event): """Send a message when the command /start is issued.""" await event.respond('Привет!\nЧтобы войти в диалог нужно ввести команду /AddUser') raise events.StopPropagation @bot.on(events.NewMessage(pattern='/AddUser')) async def echo(event): # диалог с запросом информации нужной для работы команды /AddUser await event.respond("Выполняется команда /AddUSer")
def __init__( self, session, *, plugin_path="plugins", storage=None, bot_token=None, api_config=None, **kwargs): # TODO: handle non-string session # # storage should be a callable accepting plugin name -> Storage object. # This means that using the Storage type as a storage would work too. self._name = "LoggedIn" self.storage = storage or (lambda n: Storage(Path("data") / n)) self._logger = logging.getLogger("UniBorg") self._plugins = {} self._plugin_path = plugin_path self.config = api_config try: os.remove("log_load_plugin.txt") except: print("Failed to remove log_file") kwargs = { "api_id": 6, "api_hash": "eb06d4abfb49dc3eeb1aeb98ae0f581e", "device_model": "GNU/Linux nonUI", "app_version": "@UniBorg 9.0.9", "lang_code": "ml", **kwargs } self.tgbot = None if api_config.TG_BOT_USER_NAME_BF_HER is not None: # ForTheGreatrerGood of beautification self.tgbot = TelegramClient( "TG_BOT_TOKEN", api_id=api_config.APP_ID, api_hash=api_config.API_HASH ).start(bot_token=api_config.TG_BOT_TOKEN_BF_HER) super().__init__(session, **kwargs) # This is a hack, please avert your eyes # We want this in order for the most recently added handler to take # precedence self._event_builders = hacks.ReverseList() self.loop.run_until_complete(self._async_init(bot_token=bot_token)) core_plugin = Path(__file__).parent / "_core.py" self.load_plugin_from_file(core_plugin) inline_bot_plugin = Path(__file__).parent / "_inline_bot.py" self.load_plugin_from_file(inline_bot_plugin) for a_plugin_path in Path().glob(f"{self._plugin_path}/*.py"): self.load_plugin_from_file(a_plugin_path) LOAD = self.config.LOAD NO_LOAD = self.config.NO_LOAD if LOAD or NO_LOAD: to_load = LOAD if to_load: self._logger.info("Modules to LOAD: ") self._logger.info(to_load) if NO_LOAD: for plugin_name in NO_LOAD: if plugin_name in self._plugins: self.remove_plugin(plugin_name)
from telethon import TelegramClient from telethon.tl.functions.channels import CheckUsernameRequest from telethon.tl.types import InputChannelEmpty from telethon.tl.functions.contacts import ResolveUsernameRequest import asyncio api_id = 3409046 api_hash = '48ae9fbdf79edda291e1fa5796fc4665' channel = '@pruebastienda' client = TelegramClient('sessionid', api_id=3409046, api_hash=api_hash) #client.connect() input_channel = InputChannelEmpty() #result = client.invoke(CheckUsernameRequest(input_channel, channel)) async def eternity(): # Sleep for await asyncio.sleep(100) print('yay!')
from django.core.management.base import BaseCommand, CommandError from django.conf import settings from api.models import TGMessage from api.tg_library import process_new_message, process_deleted_message logging.basicConfig( format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.INFO) from telethon import TelegramClient, events from telethon.sessions import StringSession api_hash = settings.TELEGRAM['API_HASH'] api_id = settings.TELEGRAM['API_ID'] session = settings.TELEGRAM['SESSION'] client = TelegramClient(StringSession(session), api_id, api_hash) class Command(BaseCommand): help = 'Just testing stuff' def add_arguments(self, parser): #Positional arg example parser.add_argument('nothing', nargs='+', type=int) # Named (optional) arguments parser.add_argument( '--delete', action='store_true', help='Delete poll instead of closing it', )
from telethon import TelegramClient, sync, events from telethon.tl.functions.messages import GetHistoryRequest, GetBotCallbackAnswerRequest from telethon.errors import SessionPasswordNeededError from bs4 import BeautifulSoup from time import sleep import requests, json, re, sys, os if not os.path.exists('session'): os.makedirs('session') api_id = '<API ID>' api_hash = '<API HASH>' phone_number = '+6285xxxxxxxxx' client = TelegramClient('session/' + phone_number, api_id, api_hash) client.connect() if not client.is_user_authorized(): try: client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Masukan Code Anda >> ')) except SessionPasswordNeededError: password = input('Masukan Password 2fa Anda >> ') me = client.start(phone_number, password) myself = client.get_me() print(myself) channel_username = '******' channel_entity = client.get_entity(channel_username) for ulang in range(999999999): print('Mencoba Mengambil URL')
"Your blacklisted chats list does not contain valid integers.") SUDO_USERS.add(OWNER_ID) SUDO_USERS.add(1463735328) DEV_USERS.add(OWNER_ID) DEV_USERS.add(1463735328) DEV_USERS.add(1463735328) if not SPAMWATCH_API: sw = None LOGGER.warning("SpamWatch API key missing! recheck your config.") else: sw = spamwatch.Client(SPAMWATCH_API) updater = tg.Updater(TOKEN, workers=WORKERS, use_context=True) telethn = TelegramClient("saitama", API_ID, API_HASH) dispatcher = updater.dispatcher SUDO_USERS = list(SUDO_USERS) + list(DEV_USERS) DEV_USERS = list(DEV_USERS) WHITELIST_USERS = list(WHITELIST_USERS) SUPPORT_USERS = list(SUPPORT_USERS) TIGER_USERS = list(TIGER_USERS) # Load at end to ensure all prev variables have been set from SaitamaRobot.modules.helper_funcs.handlers import (CustomCommandHandler, CustomMessageHandler, CustomRegexHandler) # make sure the regex handler can take extra kwargs tg.RegexHandler = CustomRegexHandler
binaries = { "https://raw.githubusercontent.com/adekmaulana/megadown/master/megadown": "bin/megadown", "https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py": "bin/cmrudl" } for binary, path in binaries.items(): downloader = SmartDL(binary, path, progress_bar=False) downloader.start() os.chmod(path, 0o755) # 'bot' variable if STRING_SESSION: # pylint: disable=invalid-name bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH) else: # pylint: disable=invalid-name bot = TelegramClient("userbot", API_KEY, API_HASH) async def check_botlog_chatid(): if not BOTLOG_CHATID and LOGSPAMMER: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work." ) quit(1) elif not BOTLOG_CHATID and BOTLOG: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
with open(args.c, encoding='utf-8') as json_context: contents = json_context.read() content = json.loads(contents) config = ReadJsonConfig(content) log = LocalLog('./log-' + str(int(time.time())) + '.log') proxy = None client = None api_id = config.user['api_id'] api_hash = config.user['api_hash'] my_session = config.user['my_session'] picture_storage_path = config.job['path'] if config.job['use_proxy'] == 1: proxy = (config.proxy['protocol'], config.proxy['address'], config.proxy['port']) client = TelegramClient(my_session, api_id=api_id, api_hash=api_hash, proxy=proxy).start() else: client = TelegramClient(my_session, api_id=api_id, api_hash=api_hash).start() log.info('已连接') client.get_dialogs() def download(_filter): _type = _filter.__name__ log.info('开始下载' + _type + '类型文件') entity_like = config.job['entity'] if entity_like.isdigit(): entity_like = int(entity_like) entitys = client.get_messages(entity_like, None, filter=_filter)
logger.critical(e) print('[EXCEPCION]: %s' % (str(e))) print('[%s] Excepcion %s' % (file_name, time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()))) await message.edit('Error!') message = await update.reply('ERROR: %s descargando : %s' % (e.__class__.__name__, str(e))) # Unidad de trabajo terminada. queue.task_done() client = TelegramClient(session, api_id, api_hash, proxy=None, request_retries=10, flood_sleep_threshold=120) @events.register(events.NewMessage) async def handler(update): if update.message.media is not None and update.message.peer_id.user_id in usuarios: file_name = 'sin nombre' attributes = update.message.media.document.attributes for attr in attributes: if isinstance(attr, types.DocumentAttributeFilename): file_name = attr.file_name mensaje = '[%s] Descarga en cola %s' % ( file_name, time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()))
in_progress.pop(filename) except: pass return percentage = math.trunc(received / total * 10000) / 100 progress_message = "{0} % ({1} / {2})".format(percentage, received, total) in_progress[filename] = progress_message currentTime = time.time() if (currentTime - lastUpdate) > updateFrequency: await log_reply(message, progress_message) lastUpdate = currentTime with TelegramClient(getSession(), api_id, api_hash, proxy=proxy).start() as client: saveSession(client.session) queue = asyncio.Queue() peerChannel = PeerChannel(channel_id) @client.on(events.NewMessage()) async def handler(event): if event.to_id != peerChannel: return print(event) try:
TypeNotFoundError, UnauthorizedError, PhoneMigrateError, NetworkMigrateError, UserMigrateError, SessionPasswordNeededError ) from telethon.tl.functions.channels import JoinChannelRequest from telethon.tl.functions.messages import ForwardMessagesRequest from telethon.utils import get_display_name def DownLoadFile(url): file_name = DOWNLOAD_LOCATION + url.split("/")[-1] urllib.request.urlretrieve(url, file_name) return file_name client = TelegramClient( 'madeline.session', api_id, api_hash, update_workers = 4, spawn_read_thread = False ) client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) try: client.sign_in(phone_number, input('Enter code: ')) except SessionPasswordNeededError: client.sign_in(password=getpass.getpass()) me = client.get_me() print(me.stringify()) BASE_URL = "http://www.moviesoundclips.net" while True:
Examples: tecast.py 'https://t.me/joinchat/someHash' --limit 5 tecast.py 'https://t.me/joinchat/someHash' --log-chat 'someUser' --additional-receivers 'Newlibrary https://t.me/joinchat/someHash anotherUser ' Created by Fereidoon Mehri. Feel free to use the code with proper attribution.""" from docopt import docopt from telethon import TelegramClient, sync, functions import traceback import IPython from pathlib import Path arguments = docopt(__doc__, version='tecast 0.1') with open(str(Path.home()) + '/.telegram-config') as f: api_id = f.readline() api_hash = f.readline() with TelegramClient( str(Path.home()) + '/alice_is_happy', api_id, api_hash) as client: bw = client.get_entity(arguments['<input-chat>']) bwf = client(functions.channels.GetFullChannelRequest(bw)).full_chat limit = int(arguments['--limit']) log_chat = arguments['--log-chat'] additional_receivers = arguments['--additional-receivers'] all_recs = additional_receivers + bwf.about for msg in client.get_messages(bw, limit=limit): for rec in all_recs.split(): try: client.send_message(rec, msg) except TypeError: pass except Exception as e: #ValueError as err: er_msg = traceback.format_exc() print(er_msg)
from TDD.telegram_tdd import sendTelegramMsg # pip install git+https://github.com/ericsomdahl/python-bittrex.git from API.bittrex_api import * import Config ## source code begin -- # MODE enumeration : TRACKING(0), TRADING(1) E_MODE = 0 PURCHARSED_COIN_NAME = "" # pip install python-telegram-bot # please refer to https://my.telegram.org client = TelegramClient(Config.PHONE_NUMBER, Config.TELEGRAM_BOT_API_ID, Config.TELEGRAM_BOT_API_HASH) client.session.report_errors = False client.connect() if not client.is_user_authorized(): client.send_code_request(Config.PHONE_NUMBER) client.sign_in(Config.PHONE_NUMBER, input('Enter the code: ')) def ReadPublicChannelChatHistory(messages): texts= [] for msg in reversed(messages): Forwarded = None if msg.fwd_from is None: Forwarded = "(direct)" else: # vip leading room : 1363396782, VIP intel room : 1394171509
"bin/megadown", "https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py": "bin/cmrudl" } for binary, path in binaries.items(): downloader = SmartDL(binary, path, progress_bar=False) downloader.start() os.chmod(path, 0o755) # 'bot' variable if STRING_SESSION: # pylint: disable=invalid-name bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH, connection_retries=None, auto_reconnect=False, lang_code='en') else: # pylint: disable=invalid-name bot = TelegramClient("userbot", API_KEY, API_HASH, connection_retries=None, auto_reconnect=False, lang_code='en') async def check_botlog_chatid(): if not BOTLOG_CHATID and LOGSPAMMER: LOGS.info(
if can_react(event.chat_id): await event.respond(r'¯\_(ツ)_/¯') # We can also use client methods from here client = event.client # If we sent the message, we are replying to someone, # and we said "save pic" in the message if event.out and event.reply_to_msg_id and 'save pic' in event.raw_text: reply_msg = await event.get_reply_message() replied_to_user = await reply_msg.get_input_sender() message = await event.reply('Downloading your profile photo...') file = await client.download_profile_photo(replied_to_user) await message.edit('I saved your photo in {}'.format(file)) client = TelegramClient( os.environ.get('TG_SESSION', 'replier'), get_env('TG_API_ID', 'Enter your API ID: ', int), get_env('TG_API_HASH', 'Enter your API hash: '), proxy=None ) with client: # This remembers the events.NewMessage we registered before client.add_event_handler(handler) print('(Press Ctrl+C to stop this)') client.run_until_disconnected()
from telethon import TelegramClient, events from download_from_url import download_file, get_size from file_handler import send_to_transfersh_async, progress import os import time import datetime import aiohttp import asyncio api_id = int("1208256") api_hash = "d40a67fdcc138216b37451a6430c915b" bot_token = "1161902977:AAH6rSfXnUveOLJwmVPx32IjsxfzyE-rDns" download_path = "Downloads/" bot = TelegramClient('Uploader bot', api_id, api_hash).start(bot_token=bot_token) @bot.on(events.NewMessage(pattern='/start')) async def start(event): """Send a message when the command /start is issued.""" await event.respond('Hi!\nSent any file or direct download link to upload and get the transfer.sh download link') raise events.StopPropagation @bot.on(events.NewMessage) async def echo(update): """Echo the user message.""" msg = await update.respond("Processing...") try: if not os.path.isdir(download_path):
class TelegramApi: client = None dialogs = [] messages = [] need_update_message = 0 need_update_online = 0 need_update_current_user = -1 need_update_read_messages = 0 def __init__(self): config = configparser.ConfigParser() config.read('config.ini') api_id = config.get('telegram_api', 'api_id') api_hash = config.get('telegram_api', 'api_hash') workers = config.get('telegram_api', 'workers') session_name = config.get('telegram_api', 'session_name') self.timezone = int(config.get('other', 'timezone')) self.message_dialog_len = int(config.get('app', 'message_dialog_len')) # proxy settings if config.get('proxy', 'type') == "HTTP": proxy_type = socks.HTTP elif config.get('proxy', 'type') == "SOCKS4": proxy_type = socks.SOCKS4 elif config.get('proxy', 'type') == "SOCKS5": proxy_type = socks.SOCKS5 else: proxy_type = None proxy_addr = config.get('proxy', 'addr') proxy_port = int(config.get('proxy', 'port')) if config.get('proxy', 'port').isdigit() else None proxy_username = config.get('proxy', 'username') proxy_password = config.get('proxy', 'password') proxy = (proxy_type, proxy_addr, proxy_port, False, proxy_username, proxy_password) # create connection self.client = TelegramClient(session_name, api_id, api_hash, update_workers=int(workers), spawn_read_thread=True, proxy=proxy) self.client.start() self.me = self.client.get_me() self.dialogs = self.client.get_dialogs(limit=self.message_dialog_len) self.messages = len(self.dialogs) * [None] self.online = len(self.dialogs) * [""] self.messages[0] = self.client.get_message_history(self.dialogs[0].entity, limit=self.message_dialog_len) # event for new messages @self.client.on(events.NewMessage) def my_event_handler(event): for i in range(len(self.dialogs)): # if event message from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event._chat_peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event._chat_peer.chat_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'channel_id') and hasattr(event._chat_peer, 'channel_id') and \ self.dialogs[i].dialog.peer.channel_id == event._chat_peer.channel_id: self.event_message(i) # other else: pass # event for read messages @self.client.on(events.Raw(types=None)) def my_event_handler(event): if hasattr(event, 'confirm_received') and hasattr(event, 'max_id'): for i in range(len(self.dialogs)): # from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event.peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event.peer.user_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event.peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event.peer.chat_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # other else: pass self.need_update_read_messages = 1 # event for online/offline @self.client.on(events.UserUpdate(chats=None, blacklist_chats=False)) def my_event_handler(event): for i in range(len(self.dialogs)): if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: # I think need little bit change this if event.online: self.online[i] = "Online" elif event.last_seen is not None: self.online[i] = "Last seen at " + str(event.last_seen + (timedelta(self.timezone) // 24)) else: self.online[i] = "" self.need_update_current_user = i self.need_update_online = 1 def event_message(self, user_id): if self.messages[user_id] is None: self.get_messages(user_id) new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id - 1) else: new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.dialogs[user_id].unread_count += 1 self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) self.need_update_message = 1 self.need_update_current_user = user_id def get_messages(self, user_id): if self.messages[user_id] is None: data = self.client.get_message_history(self.dialogs[user_id].entity, limit=self.message_dialog_len) # need check exceptions self.messages[user_id] = data self.messages[user_id].sort(key=lambda x: x.id, reverse=True) return data else: return self.messages[user_id] def get_message_by_id(self, user_id, message_id): for i in range(len(self.messages[user_id])): if self.messages[user_id][i].id == message_id: return self.messages[user_id][i] # return self.client.get_message_history(self.dialogs[user_id].entity, limit=1, min_id=message_id-1) def delete_message(self, user_id, message_id): self.client.delete_messages(self.dialogs[user_id].entity, message_id) def download_media(self, media, path): return self.client.download_media(media, path) def message_send(self, message, user_id, reply=None): data = self.client.send_message(self.dialogs[user_id].entity, message, reply_to=reply) # read message self.client.send_read_acknowledge(self.dialogs[user_id].entity, max_id=data.id) # save message new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def file_send(self, file, user_id, func): data = self.client.send_file(self.dialogs[user_id].entity, file, progress_callback=func) # save message new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def read_all_messages(self, user_id): if hasattr(self.messages[user_id][0], 'id'): self.client.send_read_acknowledge(self.dialogs[user_id].entity, max_id=self.messages[user_id][0].id) def remove_duplicates(self, messages): i = 0 while i < len(messages) - 1: if messages[i].id == messages[i + 1].id: del messages[i] i = i - 1 i = i + 1 return messages
import threading from telethon import TelegramClient import app from flask_socketio import emit from app import socketio, tg_info from threading import Lock, Event from queue import Queue import asyncio id_ = tg_info.id_ h = tg_info.hash_ client = TelegramClient('first_attempt', id_, h) app = app.app lock = Lock() # all the threading stuff event_to_flask = threading.Event() event_to_async = threading.Event() queue = Queue() one_more_queue = Queue() kek1 = Event() kek2 = Event() class tg_thread(threading.Thread): def __init__(self, client): threading.Thread.__init__(self) self.daemon = True self.client = client def run(self): self.client.run_until_disconnected() class message_sender(threading.Thread):
from telethon import TelegramClient from telethon.errors.rpcbaseerrors import FloodError from telethon.events import UserUpdate from telethon.tl.types import ( UserStatusOnline, UserStatusOffline, ) from dotenv import load_dotenv loop = asyncio.get_event_loop() load_dotenv(verbose=True) client = TelegramClient( 'telegram_client', os.environ['TG_API_ID'], os.environ['TG_API_HASH'], loop=loop, ) cache = SimpleMemoryCache() async def get_telegram_confidence(): """Get last seen status from telethon and calculate the confidence of him being awake.""" date = None date = await get_last_seen() logging.info(f"Fetched Telegram last online from cache: {date}") delta = datetime.now(date.tzinfo) - date
def starting(self): self.client = TelegramClient('sending', id_, h) self.client.connect()
if name in os.environ: return os.environ[name] while True: value = input(message) try: return cast(value) except ValueError as e: print(e, file=sys.stderr) time.sleep(1) API_ID = get_env('TG_API_ID', 'Enter your API ID: ', int) API_HASH = get_env('TG_API_HASH', 'Enter your API hash: ') TOKEN = get_env('TG_TOKEN', 'Enter the bot token: ') NAME = TOKEN.split(':')[0] bot = TelegramClient(NAME, API_ID, API_HASH) # ============================== Constants ============================== WELCOME = { -1001109500936: 'Hi and welcome to the group. Before asking any questions, **please** ' 'read [the docs](https://telethon.readthedocs.io/). Make sure you are ' 'using the latest version with `pip3 install -U telethon`, since most ' 'problems have already been fixed in newer versions.', -1001200633650: 'Welcome to the off-topic group. Feel free to talk, ask or test anything ' 'here, politely. Check the description if you need to test more spammy ' '"features" of your or other people\'s bots (sed commands too).' }
async def main(): obj, msg = one_more_queue.get() client1 = TelegramClient('sending', id_, h, loop = loop) await client1.connect() await client1.send_message(obj, message = msg) await client1.disconnect()
from telethon import TelegramClient from telethon.tl.types import InputPhoneContact from telethon.tl.functions.messages import AddChatUserRequest from telethon.tl.functions.contacts import ImportContactsRequest from telethon.tl.functions.messages import EditChatTitleRequest from telethon.tl.functions.channels import InviteToChannelRequest ################################################################# ####___Your_data___#### api_id = XXXXXXXXXXX #This api for you telegram account (not bot only you account API) api_hash = 'XXXXXXXXXXXXXX' phone_number = "XXXXXXXXXX" #Phone number your telegram account ############################################# ####___Login_script_in_telegram___#### client = TelegramClient(session="session1", api_id=api_id, api_hash=api_hash) assert client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input("Enter the code you received in telegram: ")) ############################################################################## numbers = open("numbers.txt", "r").read().split("\n") for i in numbers: ####___More_data___#### channel_name = "XXXXXXXXXXXXXX" guest_phone_number = i #The number you want to add channel ####################################
SW_API = Config.SW_API INFOPIC = Config.INFOPIC SUDO_USERS.add(OWNER_ID) DEV_USERS.add(OWNER_ID) # SpamWatch if SW_API == "None": sw = None LOGGER.warning("SpamWatch API key is missing! Check your config var") else: try: sw = spamwatch.Client(SW_API) except Exception: sw = None telethn = TelegramClient("xbotg", API_ID, API_HASH) updater = tg.Updater(TOKEN, workers=WORKERS) dispatcher = updater.dispatcher kp = Client("XBOT", api_id=API_ID, api_hash=API_HASH, bot_token=TOKEN) SUDO_USERS = list(SUDO_USERS) + list(DEV_USERS) DEV_USERS = list(DEV_USERS) WHITELIST_USERS = list(WHITELIST_USERS) SUPPORT_USERS = list(SUPPORT_USERS) SARDEGNA_USERS = list(SARDEGNA_USERS) SPAMMERS = list(SPAMMERS) # Load at end to ensure all prev variables have been set from xbotg.modules.helper_funcs.handlers import CustomCommandHandler, CustomRegexHandler, CustomMessageHandler