示例#1
0
def main():
    global username, replacer, client

    files = os.listdir()
    sessions = []
    for file in files:
        if file.endswith('.session'):
            sessions.append(file)

    i = 0
    phones = []
    for session in sessions:
        phones.append(session.split('.session')[0])
        client = Client(phones[i], api_id, api_hash)
        loop.run_until_complete(client.connect())

        me = loop.run_until_complete(client.get_me())
        try:
            name = me['first_name'] + ' ' + me['last_name']
        except:
            name = me['first_name']
        name = name + '\n (' + me['phone_number'] + ')'
        print(str(i + 1) + ". " + name)
        loop.run_until_complete(client.disconnect())
        i += 1

    print(str(i + 1) + ". New login")

    c = int(input("Enter valid choice: "))
    if c == len(phones) + 1:
        phone = input("Enter phone: ")
        client = Client(phone, api_id, api_hash)
        loop.run_until_complete(client.connect())
        code_hash = loop.run_until_complete(
            client.send_code(phone))['phone_code_hash']
        code = input("Enter code: ")
        loop.run_until_complete(client.sign_in(phone, code_hash, code))
    else:
        client = Client(phones[c - 1], api_id, api_hash)
        loop.run_until_complete(client.connect())

    me = loop.run_until_complete(client.get_me())
    try:
        name = me['first_name'] + ' ' + me['last_name']
    except:
        name = me['first_name']
    wel = "\nLogged in as: " + name + ' (' + me['phone_number'] + ')\n'
    print(wel)
    path = input('Enter path : ')
    username = input("Enter phone no. , channel link, group link ,etc. : ")
    replacer = os.path.dirname(path) + '/'
    upload(path)
示例#2
0
文件: core.py 项目: Cyace84/dicetime
def send_chat_list(client: Client, user: User, update: Union[Message,
                                                             CallbackQuery]):
    chats = AllowedChat.objects.filter(creator=user, status='activated')
    clean_chats = []
    for chat in chats:
        try:
            client.resolve_peer(chat.chat_id)
            clean_chats.append(chat)
        except ChannelInvalid as exc:
            logger.info(f'### Error {chat}: {type(exc)}: {exc}')

    if not clean_chats:
        text = user.choice_localized(text_name='msg-owner-empty')
        button_text = user.choice_localized(text_name='btn-owner-add-bot')
        bot = client.get_me()
        client.send_message(user.id,
                            text,
                            reply_markup=markup_add_to_chat(
                                bot.username, button_text))
        return

    text = user.choice_localized(text_name='msg-owner')
    if isinstance(update, Message):
        update.reply_text(text, reply_markup=markup_chat_list(clean_chats))
    if isinstance(update, CallbackQuery):
        update.message.edit_text(text,
                                 reply_markup=markup_chat_list(clean_chats))
示例#3
0
def help_bot(app, msg):
    me = app.get_me()
    try:
        name_module = msg.text.split(maxsplit=1)[1].replace("/", ".")
        if name_module in modules_list():
            s = importlib.import_module(f"modules.{name_module}")
            try:
                des = s.Main.des
            except:
                des = "Неизвестно"
            try:
                ver = s.Main.ver
            except:
                ver = "Неизвестно"
            try:
                cmd_list = s.Main.cmd_list
                text_cmd = ""
                for i in cmd_list.keys():
                    text_cmd += f"• {i} - {cmd_list[i]}\n"
            except:
                text_cmd = "Неизвестно"
            text = f"Информация о модуле **{name_module}:**\n\n**Описание:**\n{des}\n\n**Версия:**\n{ver}\n\n**Команды:**\n{text_cmd}"
            msg.edit(text)
        else:
            msg.edit(f"Модуль **{name_module}** не найден!")
    except IndexError:
        moduls = modules_list()
        text = f"**[KGBot](tg://resolve?domain=kgbotmodules)**\n\n**Доступные модули:**\n"
        for i in moduls:
            text += f"• {i}\n"
        text += f"\nВсего модулей: **{len(moduls)}**\n.help [name] - информация о модуле"
        msg.edit(text)
示例#4
0
文件: bot.py 项目: tuyyui/DiceBot
def added(app: Client, message: Message):
    if app.get_me().id in [i.id for i in message.new_chat_members]:
        app.send_message(
            message.chat.id,
            START_GROUP.format(Emoji.GAME_DIE),
            disable_web_page_preview=True,
        )
示例#5
0
文件: main.py 项目: giuseppegg02/asta
def onBotJoinChat(client: Client, message: Message) -> None:
    if client.get_me() not in message.new_chat_members:  # Todo -> If the bot not in new chat members
        return
    group: Chat = message.chat
    waitingToBeAcceptedGroups.append(group)
    for user_id in Database.getRegisteredUsers():
        client.send_message(user_id, "The bot has joined a new chat : " + group.title,
                            reply_markup=_getGroupAcceptKeyboard(group))
示例#6
0
 def run(self):
     app = Client("nintendo",
                  config_file='pyrogram.ini',
                  plugins=dict(root='./bot/plugins'),
                  workers=128)
     app.start()
     myself = app.get_me()
     name = myself.first_name + ' ' + myself.username
     logger.info(name)
示例#7
0
def get_diff(token: str):
    client = Client(token)
    client.workers = 1
    client.no_updates = True

    client.api_id = APP_ID
    client.api_hash = APP_HASH
    client.workdir = WORK_DIR

    try:
        client.start()
    except Exception:
        return

    uid = client.get_me().id
    req = GetDifference(1, 1, 0)
    out = open(f"{OUT_DIR}/{uid}", "w")

    while True:

        try:
            diff = client.send(req)

        except InternalServerError:
            continue

        except Unauthorized:
            break

        if isinstance(diff, DifferenceSlice):
            write_diff(out, diff.new_messages)

            req.pts = diff.intermediate_state.pts
            req.qts = diff.intermediate_state.qts
            req.date = diff.intermediate_state.date

            print(f"next pts for {uid} = {req.pts}")

        elif isinstance(diff, Difference):
            write_diff(out, diff.new_messages)
            break

        elif isinstance(diff, DifferenceTooLong):
            req.pts = diff.pts

        elif isinstance(diff, DifferenceEmpty):
            break

    if client.is_started:
        client.stop()

    if out.tell() == 0:
        out.write("[]")

    out.close()
def get_me(client: Client) -> Optional[User]:
    # Get myself
    result = None

    try:
        result = client.get_me()
    except FloodWait as e:
        raise e
    except Exception as e:
        logger.warning(f"Get me error: {e}", exc_info=True)

    return result
示例#9
0
文件: core.py 项目: Cyace84/dicetime
def _button_win(app: Client,
                user: User,
                dice_msg: Message,
                event,
                event_local=None):
    take_money_btn_text = user.choice_localized(text_name='btn-chat-win')
    take_money_msg_text = user.choice_localized(
        text_name='msg-chat-win').format(X=event.summa, coin_ticker=event.coin)
    if event_local:
        take_money_msg_text += f' + {event_local.summa} {event_local.coin}'
    bot = app.get_me()
    dice_msg.reply(take_money_msg_text,
                   reply_markup=markup_take_money(bot.username,
                                                  take_money_btn_text))
示例#10
0
def main():
    print("starting task system cli...")
    print(__version__)

    app = Client("tasksystem_bot")

    for handler in handlers_list:
        app.add_handler(handler)

    app.start()
    print(app.get_me().username)

    print("done")
    idle()
示例#11
0
def get_super_groups(app: Client) -> Generator[Chat, None, None]:
    self_id = app.get_me().id
    for dialog in app.iter_dialogs():
        dialog: Dialog
        chat = dialog.chat
        if chat.type != "supergroup":
            continue
        try:
            member = app.get_chat_member(chat.id, self_id)
            if not member.can_restrict_members:
                continue
        except Exception as e:
            print("#%s (%s): %s" % (chat.title, chat.id, repr(e)))
            continue
        yield chat
示例#12
0
def get_me(client: Client) -> Optional[User]:
    # Get myself
    result = None
    try:
        flood_wait = True
        while flood_wait:
            flood_wait = False
            try:
                result = client.get_me()
            except FloodWait as e:
                flood_wait = True
                wait_flood(e)
    except Exception as e:
        logger.warning(f"Get me error: {e}", exc_info=True)

    return result
示例#13
0
文件: main.py 项目: giuseppegg02/asta
def startAuction(client: Client, message: Message) -> None:
    if bool(runningAuctions):
        return
    sender: User = message.from_user
    group = message.chat
    administrators = [admin.user.id for admin in group.iter_members(filter="administrators")]
    cond1 = sender.id not in administrators
    cond2 = client.get_me().id not in administrators
    if cond1 or cond2:
        return
    message.delete()
    messageWords: List[str] = message.text.split(' ')
    if len(messageWords) != 2:
        return
    for auction in auctions:
        if auction.name == messageWords[1]:
            runningAuction = auction.start(group)
            _timeOut(runningAuction)
            break
示例#14
0
def help_bot(app, msg):
	me = app.get_me()
	try:
		name_module = msg.text.split(maxsplit=1)[1]
		if name_module in modules_list():
			s = importlib.import_module(f"modules.{name_module}")
			try:
				des = s.Main.des
			except:
				des = "Неизвестно"
			try:
				ver = s.Main.ver
			except:
				ver = "Неизвестно"
			try:
				cmd_list = s.Main.cmd_list
				text_cmd = ""
				for i in cmd_list.keys():
					text_cmd += f"{i} - {cmd_list[i]}\n"
			except:
				text_cmd = "Неизвестно"
			text = f"Информация о модуле **{name_module}:**\n\nОписание:\n{des}\n\nВерсия:\n{ver}\n\nКоманды:\n{text_cmd}"
			msg.edit(text)
		else:
			msg.edit(f"Модуль **{name_module}** не найден!")
	except IndexError:
		moduls = modules_list()
		text = f"**[KGBot](tg://user?id={me.id}) | [Канал](t.me/kgbotmodules)\nВведите .help [module] чтобы получить информацию о модуле\n\nДоступные модули:**\n"
		lenght = 0
		for i in moduls:
			s = importlib.import_module(f"modules.{i}")
			try:
				krat_help = s.Main.in_help
			except:
				krat_help = None
			if i == "basic":
				lenght -= 1
			else:
				text += f"• **{i}**: ```{krat_help}```\n"
			lenght += 1
		text += f"\nВсего модулей: **{lenght}**"
		msg.edit(text)
示例#15
0
def main():
    mobile_number = sms.get_mobile_number()
    # Get current account balance before signup
    print(sms.account_info)
    try:
        app = Client(session_name=mobile_number,
                     phone_number=mobile_number,
                     phone_code=phone_code_callback,
                     first_name="John",
                     last_name="Doe")

        with app:
            print(app.get_me())

        return mobile_number

    except Exception as e:
        print(e)
        print(sms.blacklist(mobile_number))
        return None
示例#16
0
def me(app: Client, msg: Message):
    me = app.get_me()
    status = me.status
    off_mode = r.get("offmode")
    if status == "offline":

        if off_mode == "on":
            try:
                txt = r.get(offtxt)
                print("done!")
                print(txt)
            except:
                txt = "User is offline please send message later!"
            app.send_message(
                msg.chat.id,
                txt,
            )
        else:
            pass
    else:
        pass
示例#17
0
import logging
from pyrogram import Client, idle
from Config import Config


logging.basicConfig(
    level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logging.getLogger("pyrogram").setLevel(logging.WARNING)


app = Client(
    "ID-Bot",
    api_id=Config.API_ID,
    api_hash=Config.API_HASH,
    bot_token=Config.BOT_TOKEN,
    plugins=dict(root="ID-Bot"),
)


# Run Bot
if __name__ == "__main__":
    app.start()  # Not using run as wanna print
    uname = app.get_me().username
    print(f"@{uname} Started Berhasil...!")
    idle()
    app.stop()
    print("Bot Berhenti. Hehe!")
from os import environ
import logging
from pyrogram import Client
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

API_ID = environ.get("TEST_TL_API_ID")
API_HASH = environ.get("TEST_TL_API_HASH")

app = Client("my_account", api_id=API_ID, api_hash=API_HASH)

app.start()
print(app.get_me())

user = "******"
res = app.send_message(user, "/start")
m = app.get_messages(res["chat"]["id"], [res["message_id"] + 1])
print("replies=========\n", m[-1])
app.stop()
示例#19
0
    while len(API_HASH) != 32:
        API_HASH = input('API HASH: ')

    app = Client(
        'sedenuserbot',
        api_id=API_ID,
        api_hash=API_HASH,
        app_version='Seden UserBot',
        device_model='DerUntergang',
        system_version='Session',
        lang_code='en',
    )

    with app:
        self = app.get_me()
        session = app.export_session_string()
        out = f'''**Hi [{self.first_name}](tg://user?id={self.id})
\nAPI_ID:** `{API_ID}`
\n**API_HASH:** `{API_HASH}`
\n**SESSION:** `{session}`
\n**NOTE: Don't give your account information to others!**'''
        out2 = 'Session successfully generated!'
        if self.is_bot:
            print(f'{session}\n{out2}')
        else:
            app.send_message('me', out)
            print('''Session successfully generated!
Please check your Telegram Saved Messages''')

elif lang == 'tr':
示例#20
0
        while PUMP_BALANCE > API.get_coin_balance('BTC')['Available']:
            print('You can\'t invest more than {}'.format(
                API.get_coin_balance('BTC')['Available']))
            PUMP_BALANCE = float(
                input("How much BTC would you like to use?: "))

    if manual:
        print('\n***Wait input data***\n')
        while True:
            try:
                PUMP_COIN = input().rstrip(' \t\r\n\0').upper()
                if PUMP_COIN != '':
                    print(PUMP_COIN)
                    callback(PUMP_COIN)
                    break
            except Exception as e:
                print(e)
            time.sleep(0.01)
    else:
        # Инициализация клиента
        client = Client(
            session_name="pyro",
            phone_number=PHONE,
            phone_code=input("code: "),
        )

        client.set_update_handler(callback)
        client.start()
        print(client.get_me().user)
        client.idle()
示例#21
0
import wget
STREAM_URL = Config.STREAM_URL
CHAT = Config.CHAT
GROUP_CALLS = {}
FFMPEG_PROCESSES = {}
RADIO = {6}
LOG_GROUP = Config.LOG_GROUP
DURATION_LIMIT = Config.DURATION_LIMIT
playlist = Config.playlist
msg = Config.msg

bot = Client("Musicplayervc",
             Config.API_ID,
             Config.API_HASH,
             bot_token=Config.BOT_TOKEN)
e = bot.get_me()
USERNAME = e.username

ydl_opts = {
    "format": "bestaudio[ext=m4a]",
    "geo-bypass": True,
    "nocheckcertificate": True,
    "outtmpl": "downloads/%(id)s.%(ext)s",
}
ydl = YoutubeDL(ydl_opts)


def youtube(url: str) -> str:
    info = ydl.extract_info(url, False)
    duration = round(info["duration"] / 60)
    try:
示例#22
0
class bot_class:
    bot_self = None

    def __init__(self):
        logger.debug('Enter bot_class.__init__()')
        config = ConfigParser()
        config.read('data/config.ini')
        self.bot = Client(config.get('bot', 'bot_token').split(':')[0],
                          config.get('bot', 'api_id'),
                          config.get('bot', 'api_hash'),
                          bot_token=config.get('bot', 'bot_token'))
        self._bot_id = int(self.bot.session_name)
        self.conn = mysqldb(config.get('database', 'host'),
                            config.get('database', 'user'),
                            config.get('database', 'password'),
                            config.get('database', 'db'),
                            autocommit=True)
        self._bot_name = None
        self.loaddatetime = datetime.datetime.now().replace(microsecond=0)
        self.groups = group_cache(self.conn, self.bot)
        self.error_message = config.get('bot', 'error_message', fallback='')
        self.init_receiver()

    def run(self):
        self.bot.start()
        try:
            self.bot.idle()
        except InterruptedError:
            logger.debug('Catch!')

    def stop(self):
        self.bot.stop()
        self.conn.close()

    @property
    def bot_id(self) -> int:
        return self._bot_id

    @property
    def bot_name(self) -> str:
        if self._bot_name is None:
            self._bot_name = self.bot.get_me().username
            logger.debug('Fetched bot username => %s', self._bot_name)
        return self._bot_name

    def new_chat_member(self, client: Client, msg: Message):
        if self.bot_id in msg.new_chat_members:
            self.groups.insert_group(msg.chat.id)
            msg.reply('Please use /setwelcome to set welcome message')
            #msg.reply('This bot is refactoring code, feature may not available during this time')
        else:
            group_setting = self.groups[msg.chat.id]
            if group_setting is None:
                group_setting = self.groups.insert_group(msg.chat.id)
            welcome_text = group_setting.welcome_text
            if welcome_text is not None:
                try:
                    last_msg = msg.reply(
                        welcome_text.replace('$name',
                                             parse_user_name(msg.from_user)),
                        parse_mode='markdown',
                        disable_web_page_preview=True).message_id
                except pyrogram.errors.ChatWriteForbidden:
                    logger.error('Got ChatWriterForbidden in %d', msg.chat.id)
                    msg.chat.leave()
                    self.groups.delete_group(msg.chat.id)
                    return
                previous_msg = self.conn.query_last_message_id(msg.chat.id)
                self.conn.insert_last_message_id(msg.chat.id, last_msg)
                if self.groups[msg.chat.id].no_welcome:
                    if previous_msg is not None:
                        client.delete_messages(msg.chat.id, previous_msg)

    def left_chat_member(self, _client: Client, msg: Message):
        if self.bot_id in msg.left_chat_member:
            self.groups.delete_group(msg.chat.id)

    def privileges_control(self, client: Client, msg: Message):
        bot_name = re.match(
            r'^\/(setwelcome|clear|status|setflag)(@[a-zA-Z_]*bot)?\s?',
            msg.text).group(2)
        if bot_name is not None and bot_name[1:] != self.bot_name:
            return
        group_info = self.groups[msg.chat.id]
        if group_info.admins is None:
            admins = client.get_chat_members(msg.chat.id,
                                             filter='administrators')
            group_info.admins = [x.user.id for x in admins]
            self.groups.update_group(msg.chat.id, group_info)
            logger.info('Updated administrator list in %d, new list is => %s',
                        msg.chat.id, group_info.admins)
        if msg.from_user.id in group_info.admins:
            raise ContinuePropagation
        else:
            if not group_info.ignore_err and self.error_message != '':
                msg.reply(self.error_message)
                try:
                    client.restrict_chat_member(
                        msg.chat.id, msg.from_user.id,
                        ChatPermissions(can_send_messages=False),
                        msg.date + 60)
                except:
                    pass

    def set_welcome_message(self, _client: Client, msg: Message):
        result = setcommand_match.match(msg.text)
        welcomemsg = str(result.group(2))
        result = gist_match.match(welcomemsg)
        if result:
            r = requests.get(welcomemsg)
            r.raise_for_status()
            welcomemsg = r.text
        if len(welcomemsg) > 2048:
            msg.reply(
                "**Error**:Welcome message is too long.(len() must smaller than 2048)",
                parse_mode='markdown')
            return
        p = self.groups[msg.chat.id]
        p.welcome_text = welcomemsg
        self.groups.update_group(msg.chat.id, p)
        msg.reply(f"**Set welcome message to:**\n{welcomemsg}",
                  parse_mode='markdown',
                  disable_web_page_preview=True)

    def clear_welcome_message(self, _client: Client, msg: Message):
        p = self.groups[msg.chat.id]
        p.welcome_text = ''
        self.groups.update_group(msg.chat.id, p)
        msg.reply("**Clear welcome message completed!**",
                  parse_mode='markdown')

    def generate_status_message(self, _client: Client, msg: Message):
        info = self.groups[msg.chat.id]
        send_and_delete(
            msg, 'Current welcome messsage: {}'.format(info.welcome_text), 10)

    def response_ping_command(self, _client: Client, msg: Message):
        send_and_delete(
            msg,
            '**Current chat_id:** `{}`\n**Your id:** `{}`\n**Bot runtime**: `{}`\n**System load avg**: `{}`'
            .format(msg.chat.id, msg.from_user.id, self.get_runtime(),
                    getloadavg()), 10)

    def set_group_prop(self, _client: Client, msg: Message):
        r = setflag_match.match(msg.text)
        if r is None:
            return send_and_delete(
                msg, 'Please read manual to use this command properly', 10)
        value = r.group(3) == '1'
        group_info = self.groups[msg.chat.id]
        if r.group(2) == 'no_welcome':
            group_info.no_welcome = value
        elif r.group(2) == 'no_blue':
            group_info.no_blue = value
        elif r.group(2) == 'ignore_err':
            group_info.ignore_err = value
        elif r.group(2) == 'no_service_msg':
            group_info.no_service_msg = value
        elif r.group(2) == 'no_new_member':
            group_info.no_new_member = value
        self.groups.update_group(msg.chat.id, group_info)
        send_and_delete(msg,
                        f'Set {r.group(2)} flag to **{value}** successfully!',
                        10)

    def init_receiver(self):
        self.bot.add_handler(
            MessageHandler(self.new_chat_member, Filters.new_chat_members))
        self.bot.add_handler(
            MessageHandler(self.left_chat_member, Filters.left_chat_member))
        self.bot.add_handler(
            MessageHandler(
                self.privileges_control, Filters.group & Filters.regex(
                    r'^\/(setwelcome|clear|status|setflag)(@[a-zA-Z_]*bot)?\s?'
                )))
        self.bot.add_handler(
            MessageHandler(
                self.set_welcome_message, Filters.group &
                Filters.regex(r'^\/setwelcome(@[a-zA-Z_]*bot)?\s((.|\n)*)$')))
        self.bot.add_handler(
            MessageHandler(
                self.clear_welcome_message,
                Filters.group & Filters.regex(r'^\/clear(@[a-zA-Z_]*bot)?$')))
        self.bot.add_handler(
            MessageHandler(
                self.generate_status_message,
                Filters.group & Filters.regex(r'^\/status(@[a-zA-Z_]*bot)?$')))
        self.bot.add_handler(
            MessageHandler(
                self.response_ping_command,
                Filters.group & Filters.regex(r'^\/ping(@[a-zA-Z_]*bot)?$')))
        self.bot.add_handler(
            MessageHandler(
                self.set_group_prop, Filters.group
                & Filters.regex(r'^\/setflag(@[a-zA-Z_]*bot)?\s?')))

    def get_runtime(self):
        return str(datetime.datetime.now().replace(microsecond=0) -
                   self.loaddatetime)
示例#23
0
@Telescopy.on_message(filters.new_chat_members & filters.me)
async def greet(client, message):
    await message.reply_text(
        '**Thanks for Adding me Here !\n\nI will Convert Square Videos or Gif When they will be send in this Chat**',
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(text="📣 Support Group 📣",
                                 url="https://t.me/FutureCodes")
        ]]))


@Telescopy.on_message(filters.private & filters.command('start'))
async def pmfilter(client, message):
    await message.reply_text(
        "**I can Convert Square Video or Gif to Circle Form...\n\nJust send me Square Video or Gif\n\nJoin @FutureCodes**",
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(text="🌟 Support Group 🌟",
                                 url=f"https://t.me/FutureCodes")
        ]]),
        quote=True)


@Telescopy.on_message(filters.group & filters.command('start'))
async def groupo(client, message):
    await message.reply_text('Hi, I am Alive', quote=True)


Telescopy.run()
hm = Telescopy.get_me()
logging.print(f"{hm.username} Deployed Successfully !!")
logging.print("Join @FutureCodes...")
示例#24
0
    MAX_FILE_SIZE = 400000000
    TG_MAX_FILE_SIZE = 14000000000
    # chunk size that should be used with requests
    CHUNK_SIZE = 100*1024


language = "english"

app = Client(
    os.environ.get("TOKEN"),
    api_id=os.environ["APP_ID"],
    api_hash=os.environ["API_HASH"])

# Automatically sets your user id

app.start()
user_id = app.get_me().id
app.stop()

# Set an error channel

log_channel = -1001249303594

# Enabled plugins

plugins = ["filtext"]

# Command prefix

prefix = "!"
示例#25
0
class bot_controller(object):
    def __init__(self):
        self.problems_load()
        self.target_group = int(config['fuduji']['target_group'])
        self.fudu_group = int(config['fuduji']['fudu_group'])

        self.bot_id = int(config['account']['api_key'].split(':')[0])
        self.emerg_contact = eval(config['account']['emerg_contact']) \
         if config.has_option('account', 'emerg_contact') and config['account']['emerg_contact'] != '' else \
         int(config['account']['owner'])
        self.app = Client(session_name='session',
                          api_id=config['account']['api_id'],
                          api_hash=config['account']['api_hash'],
                          app_version='repeater')
        self.botapp = Client(session_name=config['account']['api_key'],
                             api_id=config['account']['api_id'],
                             api_hash=config['account']['api_hash'])

        self.conn = mysqldb(config['database']['host'],
                            config['database']['user'],
                            config['database']['passwd'],
                            config['database']['db_name'], self.emerg_contact)
        self.media_sender = mediaSender(self.app.send_message, self.conn)
        self.join_group_verify = join_group_verify_class(
            self.conn, self.botapp, self.target_group, extern_load_problem_set)
        self.revoke_tracker_thread = self.join_group_verify.get_revoke_tracker_thread(
        )
        self.custom_service = custom_service_bot_class(
            config, self.conn, self.revoke_tracker_thread.send_link)
        self.db_keepAlive = Thread(target=self.conn.keep_alive, daemon=True)
        self.db_keepAlive.start()

    def init(self):
        global bot_username
        bot_username = self.botapp.get_me().username

    def problems_load(self):
        self.problem_set = extern_load_problem_set()

    def idle(self):
        return self.app.idle()

    def start(self):
        self.app.add_handler(
            MessageHandler(
                self.handle_edit,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.edited))
        self.app.add_handler(
            MessageHandler(
                self.handle_new_member,
                Filters.chat(self.target_group) & Filters.new_chat_members))
        self.app.add_handler(
            MessageHandler(
                self.handle_document,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.document))
        self.app.add_handler(
            MessageHandler(
                self.handle_photo,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.photo))
        self.app.add_handler(
            MessageHandler(
                self.handle_sticker,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.sticker))
        self.app.add_handler(
            MessageHandler(
                self.handle_gif,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.animation))
        self.app.add_handler(
            MessageHandler(
                self.handle_video,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.video))
        self.app.add_handler(
            MessageHandler(
                self.handle_speak,
                Filters.chat(self.target_group) & ~Filters.user(self.bot_id)
                & Filters.text))
        self.app.add_handler(
            MessageHandler(self.handle_incoming,
                           Filters.incoming & Filters.chat(self.fudu_group)))
        self.botapp.add_handler(CallbackQueryHandler(self.handle_callback))
        self.join_group_verify.init()
        self.app.start()
        self.botapp.start()
        self.init()
        self.custom_service.start()

    def stop(self):
        self.revoke_tracker_thread.set_stop()
        self.revoke_tracker_thread.join(1.5)
        if self.revoke_tracker_thread.is_alive():
            print('[WARN] revoke_tracker_thread still running!')
        self.custom_service.stop()
        self.botapp.stop()
        self.app.stop()

    def emerg_send_message(self, msg_str: str):
        '''
			Send message to emergancy contacts.
		'''
        if isinstance(self.emerg_contact, int):
            self.app.send_message(self.emerg_contact, msg_str, 'html')
        else:
            for user_id in self.emerg_contact:
                self.app.send_message(user_id, msg_str, 'html')

    def process_imcoming_command(self, client: Client, msg: Message):
        r = re.match(r'^\/bot (on|off)$', msg.text)
        if r is None: r = re.match(r'^\/b?(on|off)$', msg.text)
        if r:
            if not auth_system.check_ex(
                    msg.reply_to_message.from_user.id if msg.
                    reply_to_message else msg.from_user.id):
                return
            auth_system.mute_or_unmute(
                r.group(1), msg.reply_to_message.from_user.id
                if msg.reply_to_message else msg.from_user.id)
            client.delete_messages(msg.chat.id, msg.message_id)
        if msg.text == '/status':
            user_id = msg.reply_to_message.from_user.id if msg.reply_to_message else msg.from_user.id
            status = [
                str(user_id), ' summary:\n\n',
                'A' if auth_system.check_ex(user_id) else 'Una',
                'uthorized user\nBot status: ',
                '✅' if not auth_system.check_muted(user_id) else '❌'
            ]
            sleep_to_delete(
                client, msg.chat.id,
                (msg.message_id, msg.reply(''.join(status), True).message_id))
            del status
        elif msg.text.startswith('/p'):
            if msg.text.startswith('/promote'):
                if len(msg.text.split()) == 1:
                    if msg.reply_to_message is None or not auth_system.check_ex(
                            msg.reply_to_message.from_user.id):
                        self.botapp.send_message(
                            msg.chat.id,
                            'Please reply to an Authorized user.',
                            reply_to_message_id=msg.message_id)
                        return
                    user_id = msg.reply_to_message.from_user.id
                else:
                    user_id = int(msg.text.split()[1])
                self.botapp.send_message(
                    msg.chat.id,
                    'Please use bottom to make sure you want to add {} to Administrators'
                    .format(build_html_parse.parse_user(user_id)),
                    parse_mode='markdown',
                    reply_to_message_id=msg.message_id,
                    reply_markup=InlineKeyboardMarkup(
                        inline_keyboard=[[
                            InlineKeyboardButton(text='Yes, confirm',
                                                 callback_data='promote {}'.
                                                 format(user_id).encode())
                        ],
                                         [
                                             InlineKeyboardButton(
                                                 text='Cancel',
                                                 callback_data=b'cancel d')
                                         ]]))
            else:
                if not auth_system.check_ex(msg.from_user.id): return
                self.botapp.promote_chat_member(self.target_group,
                                                int(msg.from_user.id),
                                                True,
                                                can_delete_messages=True,
                                                can_restrict_members=True,
                                                can_invite_users=True,
                                                can_pin_messages=True,
                                                can_promote_members=True)
                self.botapp.send_message(
                    msg.chat.id,
                    '[Emergency]: Privileges has been promoted',
                    reply_to_message_id=msg.message_id)
            return
        if msg.reply_to_message:
            if msg.text == '/del':
                try:
                    client.forward_messages(
                        msg.chat.id, self.target_group,
                        self.conn.get_reply_id_Reverse(msg))
                    self.botapp.delete_messages(
                        self.target_group, self.conn.get_reply_id_Reverse(msg))
                except:
                    client.send_message(msg.chat.id,
                                        traceback.format_exc(),
                                        disable_web_page_preview=True)
                try:
                    client.delete_messages(
                        int(config['fuduji']['fudu_group']),
                        [msg.message_id, msg.reply_to_message.message_id])
                except:
                    pass
            elif msg.text == '/getid':
                user_id = self.conn.get_user_id(msg)
                client.send_message(
                    msg.chat.id,
                    'user_id is `{}`'.format(
                        user_id['user_id'] if user_id is not None and
                        user_id['user_id'] != 0 else 'ERROR_INVALID_USER_ID'),
                    parse_mode='markdown',
                    reply_to_message_id=msg.reply_to_message.message_id)
            elif msg.text == '/get' and self.conn.get_reply_id_Reverse(msg):
                try:
                    client.forward_messages(
                        int(config['fuduji']['fudu_group']), self.target_group,
                        self.conn.get_reply_id_Reverse(msg))
                except:
                    client.send_message(
                        msg.chat.id,
                        traceback.format_exc().splitlines()[-1])
            elif msg.text == '/getn':
                pass
            elif msg.text == '/fw':
                self.conn.insert_ex(
                    self.botapp.forward_messages(
                        self.target_group, self.target_group,
                        self.conn.get_reply_id_Reverse(msg)).message_id,
                    msg.message_id)
            elif msg.text.startswith('/ban'):
                user_id = self.conn.get_user_id(msg)
                if len(msg.text) == 4:
                    restrict_time = 0
                else:
                    r = re.match(r'^([1-9]\d*)(s|m|h|d)$', msg.text[5:])
                    if r is not None:
                        restrict_time = int(r.group(1)) * {
                            's': 1,
                            'm': 60,
                            'h': 60 * 60,
                            'd': 60 * 60 * 24
                        }.get(r.group(2))
                    else:
                        self.botapp.send_message(
                            msg.chat.id,
                            'Usage: `/ban` or `/ban <Duration>`',
                            reply_to_message_id=msg.message_id,
                            parse_mode='markdown')
                if user_id is not None and user_id['user_id'] != 0:
                    if user_id['user_id'] not in auth_system.whitelist:
                        self.botapp.send_message(
                            msg.chat.id,
                            'What can {} only do? Press the button below.\nThis confirmation message will expire after 20 seconds.'
                            .format(
                                build_html_parse.parse_user(
                                    user_id['user_id'])),
                            reply_to_message_id=msg.message_id,
                            parse_mode='markdown',
                            reply_markup=InlineKeyboardMarkup(inline_keyboard=[
                                [
                                    InlineKeyboardButton(
                                        text='READ',
                                        callback_data='res {} read {}'.format(
                                            restrict_time,
                                            user_id['user_id']).encode())
                                ],
                                [
                                    InlineKeyboardButton(
                                        text='SEND_MESSAGES',
                                        callback_data='res {} write {}'.format(
                                            restrict_time,
                                            user_id['user_id']).encode()),
                                    InlineKeyboardButton(
                                        text='SEND_MEDIA',
                                        callback_data='res {} media {}'.format(
                                            restrict_time,
                                            user_id['user_id']).encode())
                                ],
                                [
                                    InlineKeyboardButton(
                                        text='SEND_STICKERS',
                                        callback_data='res {} stickers {}'.
                                        format(restrict_time,
                                               user_id['user_id']).encode()),
                                    InlineKeyboardButton(
                                        text='EMBED_LINKS',
                                        callback_data='res {} link {}'.format(
                                            restrict_time,
                                            user_id['user_id']).encode())
                                ],
                                [
                                    InlineKeyboardButton(
                                        text='Cancel', callback_data=b'cancel')
                                ]
                            ]))
                    else:
                        self.botapp.send_message(
                            msg.chat.id,
                            'ERROR_WHITELIST_USER_ID',
                            reply_to_message_id=msg.message_id)
                else:
                    self.botapp.send_message(
                        msg.chat.id,
                        'ERROR_INVALID_USER_ID',
                        reply_to_message_id=msg.message_id)
            elif msg.text == '/kick':
                user_id = self.conn.get_user_id(msg)
                if user_id is not None and user_id['user_id'] != 0:
                    if user_id['user_id'] not in auth_system.whitelist:
                        self.botapp.send_message(
                            msg.chat.id,
                            'Do you really want to kick {}?\nIf you really want to kick this user, press the button below.\nThis confirmation message will expire after 15 seconds.'
                            .format(
                                build_html_parse.parse_user(
                                    user_id['user_id'])),
                            reply_to_message_id=msg.message_id,
                            parse_mode='markdown',
                            reply_markup=InlineKeyboardMarkup(inline_keyboard=[
                                [
                                    InlineKeyboardButton(
                                        text='Yes, kick it',
                                        callback_data=b' '.join((
                                            b'kick',
                                            str(msg.from_user.id).encode(),
                                            str(user_id['user_id']).encode())))
                                ],
                                [
                                    InlineKeyboardButton(
                                        text='No', callback_data=b'cancel')
                                ],
                            ]))
                    else:
                        self.botapp.send_message(
                            msg.chat.id,
                            'ERROR_WHITELIST_USER_ID',
                            reply_to_message_id=msg.message_id)
                else:
                    self.botapp.send_message(
                        msg.chat.id,
                        'ERROR_INVALID_USER_ID',
                        reply_to_message_id=msg.message_id)
        else:  # Not reply message
            if msg.text == '/ban':
                client.send_message(
                    msg.chat.id,
                    'Reply to the user you wish to restrict, if you want to kick this user, please use the /kick command.'
                )
            elif msg.text == '/join':
                pass
            elif msg.text.startswith('/set'):
                auth_system.user_suffix[
                    msg.from_user.id] = msg.text.split()[-1]
                client.send_message(msg.chat.id,
                                    'Set suffix to `{}`'.format(
                                        msg.text.split()[-1]),
                                    'markdown',
                                    reply_to_message_id=msg.message_id)

    def func_auth_process(self, client: Client, msg: Message):
        if not auth_system.check_ex(msg.from_user.id):
            msg.reply('Permission denied')
            return
        if msg.reply_to_message.from_user:
            if auth_system.check_ex(msg.reply_to_message.from_user.id):
                msg.reply('Authorized')
            else:
                self.botapp.send_message(
                    msg.chat.id,
                    'Do you want to authorize {} ?\nThis confirmation message will expire after 20 seconds.'
                    .format(
                        build_html_parse.parse_user(
                            msg.reply_to_message.from_user.id)),
                    reply_to_message_id=msg.message_id,
                    parse_mode='markdown',
                    reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                        InlineKeyboardButton(
                            text='Yes',
                            callback_data='auth {} add'.format(
                                msg.reply_to_message.from_user.id).encode()),
                        InlineKeyboardButton(text='No',
                                             callback_data=b'cancel')
                    ]]))
        else:
            client.send_message(msg.chat.id,
                                'Unexpected error.',
                                reply_to_message_id=msg.message_id)

    def cross_group_forward_request(self, msg: Message):
        kb = [[
            InlineKeyboardButton(text='Yes, I know what I\'m doing.',
                                 callback_data=b'fwd original')
        ],
              [
                  InlineKeyboardButton(text='Yes, but don\'t use forward.',
                                       callback_data=b'fwd text')
              ],
              [
                  InlineKeyboardButton(text='No, please don\'t.',
                                       callback_data=b'cancel d')
              ]]
        if msg.text is None: kb.pop(1)
        self.botapp.send_message(
            msg.chat.id,
            '<b>Warning:</b> You are requesting forwarding an authorized user\'s message to the main group, please comfirm your action.',
            'html',
            reply_to_message_id=msg.message_id,
            reply_markup=InlineKeyboardMarkup(inline_keyboard=kb))
        del kb

    def handle_new_member(self, client: Client, msg: Message):
        for new_user_id in (x.id for x in msg.new_chat_members):
            # Exam check goes here
            try:
                if not self.join_group_verify.query_user_passed(new_user_id):
                    self.botapp.kick_chat_member(self.target_group,
                                                 new_user_id)
                    self.botapp.send_message(
                        self.fudu_group,
                        'Kicked challenge failure user {}'.format(
                            build_html_parse.parse_user(new_user_id)),
                        'markdown',
                    )
            except:
                traceback.print_exc()
        self.conn.insert(
         msg,
         client.send_message(
          self.fudu_group,
          '`{}` invite `{}` joined the group'.format(
           build_html_parse.user_name(msg.from_user).full_name,
           '`,`'.join(
            build_html_parse.user_name(user).full_name for user in msg.new_chat_members
           )
          ),
          'markdown'
         ) \
         if msg.new_chat_members[0].id != msg.from_user.id else \
          client.send_message(
           self.fudu_group,
           '`{}` joined the group'.format(
            '`,`'.join(
             build_html_parse.user_name(user).full_name for user in msg.new_chat_members
            )
           ),
           'markdown'
          )
         )

    def handle_edit(self, client: Client, msg: Message):
        if msg.via_bot and msg.via_bot.id == 166035794: return
        if self.conn.get_id(msg.message_id) is None:
            time.sleep(3)
            if self.conn.get_id(msg.message_id) is None:
                print(msg)
                return print('Editing Failure: get_id return None')
        try:
            (client.edit_message_text if msg.text else
             client.edit_message_caption)(self.fudu_group,
                                          self.conn.get_id(msg.message_id),
                                          build_html_parse(msg).call(), 'html')
        except:
            traceback.print_exc()

    def handle_document(self, client: Client, msg: Message):
        self.media_sender.put((client.send_document, msg, msg.document, False))

    def handle_photo(self, client: Client, msg: Message):
        self.media_sender.put(
            (client.send_photo, msg, msg.photo.sizes[0], False))

    def handle_sticker(self, client: Client, msg: Message):
        self.conn.insert(
            msg,
            client.send_message(
                self.fudu_group,
                '{} {} sticker'.format(
                    build_html_parse(msg).call(), msg.sticker.emoji),
                'html',
                True,
                reply_to_message_id=self.conn.get_reply_id(msg),
            ))

    def handle_gif(self, client: Client, msg: Message):
        self.media_sender.put(
            (client.send_animation, msg, msg.animation, False))

    def handle_video(self, client: Client, msg: Message):
        self.media_sender.put((client.send_video, msg, msg.video, False))

    def handle_speak(self, client: Client, msg: Message):
        if msg.text.startswith('/') and re.match(r'^\/\w+(@\w*)?$', msg.text):
            return
        self.conn.insert(
            msg,
            client.send_message(
                self.fudu_group,
                build_html_parse(msg).call(),
                'html',
                reply_to_message_id=self.conn.get_reply_id(msg),
                disable_web_page_preview=True))

    def handle_incoming(self, client: Client, msg: Message):
        client.send(
            api.functions.channels.ReadHistory(
                client.resolve_peer(msg.chat.id), msg.message_id))
        if msg.text == '/auth' and msg.reply_to_message:
            return self.func_auth_process(client, msg)
        if not auth_system.check_ex(msg.from_user.id): return
        if msg.text and re.match(
                r'^\/(bot (on|off)|del|getn?|fw|ban( (([1-9]\d*)(s|m|h|d)|f))?|kick( confirm| -?\d+)?|status|b?o(n|ff)|join|p(romote( \d+)?)?|set [a-zA-Z])$',
                msg.text):
            return self.process_imcoming_command(client, msg)
        if msg.text and msg.text.startswith('/') and re.match(
                r'^\/\w+(@\w*)?$', msg.text):
            return
        if auth_system.check_muted(msg.from_user.id) or (
                msg.text and msg.text.startswith('//')) or (
                    msg.caption and msg.caption.startswith('//')):
            return

        if msg.forward_from or msg.forward_from_chat:
            if msg.forward_from:
                if msg.forward_from.is_self: return
                elif auth_system.check_ex(msg.forward_from.id):
                    return self.cross_group_forward_request(msg)
            self.conn.insert_ex(
                self.botapp.forward_messages(self.target_group,
                                             self.fudu_group,
                                             msg.message_id).message_id,
                msg.message_id)
        elif msg.text and (not msg.edit_date or
                           (msg.edit_date and
                            self.conn.get_id(msg.message_id, True) is None)):
            self.conn.insert_ex(
                self.botapp.send_message(
                    self.target_group,
                    build_html_parse(msg).split_offset(),
                    'html',
                    True,
                    reply_to_message_id=self.conn.get_reply_id_Reverse(msg),
                ).message_id, msg.message_id)
        elif msg.photo:
            self.media_sender.Locker.acquire()
            msg.download('tmp.jpg')
            self.media_sender.put((self.botapp.send_photo, msg,
                                   media_path('downloads/tmp.jpg'), True),
                                  True)
        elif msg.video:
            self.media_sender.put(
                (self.botapp.send_video, msg, msg.video, True), True)
        elif msg.document:
            self.media_sender.put(
                (self.botapp.send_document, msg, msg.document, True), True)
        elif msg.edit_date:
            try:
                (self.botapp.edit_message_text
                 if msg.text else self.botapp.edit_message_caption)(
                     self.target_group,
                     self.conn.get_id(msg.message_id, True),
                     build_html_parse(msg).split_offset(),
                     parse_mode='html',
                     disable_web_page_preview=True)
            except:
                traceback.print_exc()
        elif msg.sticker:
            self.media_sender.put(
                (self.botapp.send_sticker, msg, msg.sticker, True), True)

    def handle_callback(self, client: Client, msg: CallbackQuery):
        msg.data = msg.data.decode(errors='ignore')
        try:
            if msg.data.startswith('cancel') or msg.data == 'rm':
                msg.answer(
                    msg.id,
                    'Canceled' if not msg.data == 'rm' else 'Button removed')
                if msg.data.endswith('d'):
                    client.delete_messages(msg.message.chat.id,
                                           msg.message.message_id)
                else:
                    client.edit_message_reply_markup(msg.message.chat.id,
                                                     msg.message.message_id)
            if self.join_group_verify is not None and self.join_group_verify.click_to_join(
                    client, msg):
                return
            if msg.data.startswith('res'):
                if time.time() - msg.message.date > 20:
                    raise OperationTimeoutError()
                _, dur, _type, _user_id = msg.data.split()
                if client.restrict_chat_member(
                        self.target_group, int(_user_id),
                        int(time.time()) + int(dur),
                        **({
                            'write': {
                                'can_send_messages': True
                            },
                            'media': {
                                'can_send_media_messages': True
                            },
                            'stickers': {
                                'can_send_other_messages': True
                            },
                            'link': {
                                'can_add_web_page_previews': True
                            },
                            'read': {}
                        }.get(_type))):
                    msg.answer('The user is restricted successfully.')
                    client.edit_message_text(
                        msg.message.chat.id,
                        msg.message.message_id,
                        'Restrictions applied to {} Duration: {}'.format(
                            build_html_parse.parse_user(_user_id),
                            '{}s'.format(dur) if int(dur) else 'Forever'),
                        parse_mode='markdown',
                        reply_markup=InlineKeyboardMarkup([[
                            InlineKeyboardButton(
                                text='UNBAN',
                                callback_data='unban {}'.format(
                                    _user_id).encode())
                        ]]))

            elif msg.data.startswith('unban'):
                if client.restrict_chat_member(self.target_group,
                                               int(msg.data.split()[-1]), 0,
                                               True, True, True, True):
                    msg.answer('Unban successfully')
                    client.edit_message_reply_markup(msg.message.chat.id,
                                                     msg.message.message_id)
            elif msg.data.startswith('auth'):
                if time.time() - msg.message.date > 20:
                    raise OperationTimeoutError()
                auth_system.add_user(msg.data.split()[1])
                msg.answer('{} added to the authorized group'.format(
                    msg.data.split()[1]))
                client.edit_message_text(
                    msg.message.chat.id, msg.message.message_id,
                    '{} added to the authorized group'.format(
                        msg.data.split()[1]))
                with open('config.ini', 'w') as fout:
                    config.write(fout)
            elif msg.data.startswith('fwd'):
                if time.time() - msg.message.date > 30:
                    raise OperationTimeoutError()
                if 'original' in msg.data:
                    self.conn.insert_ex(
                        client.forward_messages(
                            self.target_group, msg.message.chat.id, msg.
                            message.reply_to_message.message_id).message_id,
                        msg.message.reply_to_message.message_id)
                else:
                    self.conn.insert_ex(
                        client.send_message(
                            self.target_group,
                            build_html_parse(
                                msg.message.reply_to_message).split_offset(),
                            'html').message_id,
                        msg.message.reply_to_message.message_id)
                msg.answer('Forward successfully')
                client.delete_messages(msg.message.chat.id,
                                       msg.message.message_id)
            elif msg.data.startswith('kick'):
                if not msg.data.startswith(
                        'kickc') and msg.from_user.id != int(
                            msg.data.split()[-2]):
                    raise OperatorError()
                if 'true' not in msg.data:
                    if not msg.data.startswith(
                            'kickc') and time.time() - msg.message.date > 15:
                        raise OperationTimeoutError()
                    args = [
                        msg.message.chat.id,
                        msg.message.message_id,
                        'Press the button again to kick {}\nThis confirmation message will expire after 10 seconds.'
                        .format(
                            build_html_parse.parse_user(msg.data.split()[-1])),
                    ]
                    if msg.data.startswith('kickc'):
                        args.pop(1)
                        r = msg.data.split()
                        r.insert(1, msg.from_user.id)
                        msg.data = ' '.join(str(x) for x in r)
                        del r
                    kwargs = {
                        'parse_mode':
                        'markdown',
                        'reply_markup':
                        InlineKeyboardMarkup(
                            inline_keyboard=[[
                                InlineKeyboardButton(
                                    text='Yes, please.',
                                    callback_data=b' '.join((
                                        b'kick true', ' '.join(
                                            msg.data.split()[1:]).encode())))
                            ],
                                             [
                                                 InlineKeyboardButton(
                                                     text='Cancel',
                                                     callback_data=b'cancel')
                                             ]])
                    }
                    (client.send_message if msg.data.startswith('kickc') else
                     client.edit_message_text)(*args, **kwargs)
                    msg.answer(
                        'Please press again to make sure. Do you really want to kick {} ?'
                        .format(msg.data.split()[-1]), True)
                else:
                    if msg.message.edit_date:
                        if time.time() - msg.message.edit_date > 10:
                            raise OperationTimeoutError()
                    else:
                        if time.time() - msg.message.date > 10:
                            raise OperationTimeoutError()
                    client.kick_chat_member(self.target_group,
                                            int(msg.data.split()[-1]))
                    msg.answer('Kicked {}'.format(msg.data.split()[-1]))
                    client.edit_message_text(
                        msg.message.chat.id, msg.message.message_id,
                        'Kicked {}'.format(
                            build_html_parse.parse_user(msg.data.split()[-1])))
                    #app.send_message(self.fudu_group, 'Kicked {}'.format(msg.message.entities[0].user.id))
                #client.delete_messages(msg.message.chat.id, msg.message.message_id)
            elif msg.data.startswith('promote'):
                if not msg.data.endswith('undo'):
                    if time.time() - msg.message.date > 10:
                        raise OperationTimeoutError()
                    self.botapp.promote_chat_member(self.target_group,
                                                    int(msg.data.split()[1]),
                                                    True,
                                                    can_delete_messages=True,
                                                    can_restrict_members=True,
                                                    can_invite_users=True,
                                                    can_pin_messages=True,
                                                    can_promote_members=True)
                    msg.answer('Promote successfully')
                    client.edit_message_text(
                        msg.message.chat.id,
                        msg.message.message_id,
                        'Promoted {}'.format(
                            build_html_parse.parse_user(
                                int(msg.data.split()[1]))),
                        parse_mode='markdown',
                        reply_markup=InlineKeyboardMarkup(inline_keyboard=[
                            [
                                InlineKeyboardButton(text='UNDO',
                                                     callback_data=' '.join((
                                                         msg.data,
                                                         'undo')).encode())
                            ],
                            [
                                InlineKeyboardButton(text='remove button',
                                                     callback_data=b'rm')
                            ]
                        ]))
                else:
                    self.botapp.promote_chat_member(self.target_group,
                                                    int(msg.data.split()[1]),
                                                    False,
                                                    can_delete_messages=False,
                                                    can_invite_users=False,
                                                    can_restrict_members=False)
                    msg.answer('Undo Promote successfully')
                    client.edit_message_text(
                        msg.message.chat.id,
                        msg.message.message_id,
                        'Unpromoted {}'.format(
                            build_html_parse.parse_user(
                                int(msg.data.split()[1]))),
                        parse_mode='markdown')
        except OperationTimeoutError:
            msg.answer('Confirmation time out')
            client.edit_message_reply_markup(msg.message.chat.id,
                                             msg.message.message_id)
        except OperatorError:
            msg.answer(
                'The operator should be {}.'.format(msg.data.split()[-2]),
                True)
        except:
            self.app.send_message(int(config['fuduji']['help_group']),
                                  traceback.format_exc().splitlines()[-1])
            traceback.print_exc()
示例#26
0
# Telegram - Twitter - Bot
# Github.com/New-dev0/TgTwitterBot
# CopyLeft AGPLv3 (C) 2020 The Authors
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from Configs import Var
from pyrogram import Client, idle

import logging
logging.basicConfig(level=logging.WARNING)

Client = Client("TgTwitterBot",
                api_id=Var.API_ID,
                api_hash=Var.API_HASH,
                bot_token=Var.BOT_TOKEN,
                plugins=dict(root="twitterbot/plugins"))

Client.start()

Client = Client.get_me()
print(f"@{Client.username} Deployed Successfully!")
print("Your Tg-Twitter-Bot is Alive 🎉")

idle()
示例#27
0
            print(file)
    exit()
elif account == "--add":
    num = input("Inserisci il numero della sessione: ")
    app = Client(num, api_id=settings.id, api_hash=settings.hash)
    app.start()
    try:
        app.join_chat(settings.chat)
    except:
        pass
    app.stop()
    exit()
else:
    print("I possibili flag sono:\n--all (Avvia tutte le sessioni)\n--list (Fa vedere tutte le sessioni disponibili)\n--add (Aggiunge un account)\n--single (Avvia una sola sessione)")
    exit()

for app in apps:
    app.add_handler(MessageHandler(stop, filters.regex("stop") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(check, filters.regex("check") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(msgstorm, filters.regex("msgstorm") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(update, filters.regex("update") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(join, filters.regex("join") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(leaveAll, filters.regex("leaveall") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(aggiungiDB, filters.regex("dbadd") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(aggiungi, filters.regex("aggiungi") & filters.chat(settings.chatid)))
    app.add_handler(MessageHandler(leave, filters.regex("leave") & filters.chat(settings.chatid)))
    app.start()
    print(str(app.get_me()["phone_number"]) + " avviato")

idle()
示例#28
0
else:
    app2 = Client(SESSION_STRING, api_id=API_ID, api_hash=API_HASH)

aiohttpsession = ClientSession()

arq = ARQ(ARQ_API_URL, ARQ_API_KEY, aiohttpsession)

app = Client("wbb", bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH)

print("[INFO]: STARTING BOT CLIENT")
app.start()
print("[INFO]: STARTING USERBOT CLIENT")
app2.start()

print("[INFO]: GATHERING PROFILE INFO")
x = app.get_me()
y = app2.get_me()

BOT_ID = x.id
BOT_NAME = x.first_name + (x.last_name or "")
BOT_USERNAME = x.username
BOT_MENTION = x.mention
BOT_DC_ID = x.dc_id

USERBOT_ID = y.id
USERBOT_NAME = y.first_name + (y.last_name or "")
USERBOT_USERNAME = y.username
USERBOT_MENTION = y.mention
USERBOT_DC_ID = y.dc_id

if USERBOT_ID not in SUDOERS:
示例#29
0
from bot.config import Config
from pyrogram import Client

API_ID = Config.API_ID
API_HASH = Config.API_HASH
BOT_TOKEN = Config.BOT_TOKEN

NYAA = Client("Nyaa", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
with NYAA:
    botname = NYAA.get_me().username
示例#30
0
文件: tgpurge.py 项目: zpcol/TGClean
import config

print(" ")
print("TGPurge Cleaning Script")

# Create client object with name
print(" ")
print(" - Starting client")
app = Client("TGClean", api_id=config.tg_api_id, api_hash=config.tg_api_hash)
app.start()

print(" ")
print(" - Starting delete routine")

selfid = app.get_me().id

for target in config.targets:

    print(" ")
    print(" - Deleting messages older than " + str(target.delete_before_days) +
          " days")
    delete_before = int(time.time() -
                        (target.delete_before_days * 24 * 60 * 60))

    for chat in target.chatlist:

        # Get target's chat ID and title
        try:
            chatobj = app.get_chat(chat)
        except (ChannelInvalid, PeerIdInvalid, UsernameInvalid, ValueError):