async def inline_id_handler(event: events.InlineQuery.Event): builder = event.builder inp = event.pattern_match.group(1) if event.query.user_id == bot.uid: sn = urllib.parse.quote_plus(inp) results = [] sl = "https://api.sumanjay.cf/torrent/?query=" + sn try: op = requests.get(url=sl, timeout=10).json() except: pass ed = len(op) if ed == 0: resultm = builder.article( title="No Result", description="Try Again With correct Spelling", text="**No Matching Found**", buttons=[ [ Button.switch_inline("Search Again", query="torrent ", same_peer=True) ], ], ) await event.answer([resultm]) return if ed > 30: for i in range(30): ds = op[i]["age"] ops = op[i]["leecher"] ssk = op[i]["magnet"] okk = op[i]["name"] sizes = op[i]["size"] type = op[i]["type"] seeders = op[i]["seeder"] ok = f"**Title :** `{okk}` \n**Size :** `{sizes}` \n**Type :** `{type}` \n**Seeder :** `{seeders}` \n**Leecher :** `{ops}` \n**Magnet :** `{ssk}` " me = f"Size : {sizes} Type : {type} Age : {ds}" results.append(await event.builder.article( title=okk, description=me, text=ok, buttons=Button.switch_inline("Search Again", query="tor ", same_peer=True), )) else: for dz in op: siz = dz["size"] typ = dz["type"] seede = dz["seeder"] ag = dz["age"] leech = dz["leecher"] mag = dz["magnet"] nam = dz["name"] all = f"**Title :** `{nam}` \n**Size :** `{siz}` \n**Type :** `{typ}` \n**Seeder :** `{seede}` \n**Leecher :** `{leech}` \n**Magnet :** `{mag}` " mi = f"Size : {siz} Type : {typ} Age : {ag}" results.append(await event.builder.article( title=nam, description=mi, text=all, buttons=[ Button.switch_inline("Search Again", query="tor ", same_peer=True) ], )) await event.answer(results) if not event.query.user_id == bot.uid: resultm = builder.article( title="me not your bot", description="Mind Your Business", text="Hey U Must Use https://github.com/legendx22/LEGEND-BOT ", buttons=[ [ Button.switch_inline("Search Again", query="tor ", same_peer=True) ], ], ) await event.answer([resultm]) return
async def logbtn(conv, SENDER, path, msg, page, filelist): '''定义log日志按钮''' mybtn = [ Button.inline('上一页', data='up'), Button.inline('下一页', data='next'), Button.inline('上级', data='updir'), Button.inline('取消', data='cancel') ] try: if filelist: markup = filelist newmarkup = markup[page] if mybtn not in newmarkup: newmarkup.append(mybtn) else: dir = os.listdir(path) dir.sort() markup = [Button.inline(file, data=str(file)) for file in dir] markup = split_list(markup, 3) if len(markup) > 30: markup = split_list(markup, 30) newmarkup = markup[page] newmarkup.append(mybtn) else: newmarkup = markup if path == _JdDir: newmarkup.append([Button.inline('取消', data='cancel')]) else: newmarkup.append([ Button.inline('上级', data='updir'), Button.inline('取消', data='cancel') ]) msg = await client.edit_message(msg, '请做出您的选择:', buttons=newmarkup) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await client.edit_message(msg, '对话已取消') conv.cancel() return None, None, None, None elif res == 'next': page = page + 1 if page > len(markup) - 1: page = 0 return path, msg, page, markup elif res == 'up': page = page - 1 if page < 0: page = len(markup) - 1 return path, msg, page, markup elif res == 'updir': path = '/'.join(path.split('/')[:-1]) logger.info(path) if path == '': path = _JdDir return path, msg, page, None elif os.path.isfile(path + '/' + res): msg = await client.edit_message(msg, '文件发送中,请注意查收') await conv.send_file(path + '/' + res) msg = await client.edit_message(msg, res + '发送成功,请查收') conv.cancel() return None, None, None, None else: return path + '/' + res, msg, page, None except exceptions.TimeoutError: msg = await client.edit_message(msg, '选择已超时,本次对话已停止') return None, None, None, None except Exception as e: msg = await client.edit_message( msg, 'something wrong,I\'m sorry\n' + str(e)) logger.error('something wrong,I\'m sorry\n' + str(e)) return None, None, None, None
async def myedit(conv, SENDER, path, msg, page, filelist): mybtn = [ Button.inline('上一页', data='up'), Button.inline('下一页', data='next'), Button.inline('上级', data='updir'), Button.inline('取消', data='cancel') ] mybtn2 = [[ Button.inline('上一页', data='up'), Button.inline('下一页', data='next'), Button.inline('取消', data='cancel') ], [ Button.inline('上十页', data='up10'), Button.inline('下十页', data='next10'), Button.inline('编辑', data='edit') ]] try: if filelist and type(filelist[0][0]) == str: markup = filelist newmarkup = markup[page] msg = await client.edit_message(msg, "".join(newmarkup), buttons=mybtn2) else: if filelist: markup = filelist newmarkup = markup[page] if mybtn not in newmarkup: newmarkup.append(mybtn) else: dir = os.listdir(path) dir.sort() markup = [Button.inline(file, data=str(file)) for file in dir] markup = split_list(markup, 3) if len(markup) > 30: markup = split_list(markup, 30) newmarkup = markup[page] newmarkup.append(mybtn) else: newmarkup = markup if path == _JdDir: newmarkup.append([Button.inline('取消', data='cancel')]) else: newmarkup.append([ Button.inline('上级', data='updir'), Button.inline('取消', data='cancel') ]) msg = await client.edit_message(msg, '请做出您的选择:', buttons=newmarkup) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await client.edit_message(msg, '对话已取消') conv.cancel() return None, None, None, None, None elif res == 'next': page = page + 1 if page > len(markup) - 1: page = 0 return path, msg, page, markup elif res == 'up': page = page - 1 if page < 0: page = len(markup) - 1 return path, msg, page, markup elif res == 'next10': page = page + 10 if page > len(markup) - 1: page = 0 return path, msg, page, markup elif res == 'up10': page = page - 10 if page < 0: page = len(markup) - 1 return path, msg, page, markup elif res == 'updir': path = '/'.join(path.split('/')[:-1]) if path == '': path = _JdDir return path, msg, page, None elif res == 'edit': await client.send_message(chat_id, '请复制并修改以下内容,修改完成后发回机器人,2分钟内有效') await client.delete_messages(chat_id, msg) msg = await conv.send_message("".join(newmarkup)) resp = await conv.get_response() markup[page] = resp.raw_text.split('\n') for a in range(len(markup[page])): markup[page][a] = markup[page][a] + '\n' shutil.copy(path, path + '.bak') with open(path, 'w+', encoding='utf-8') as f: markup = ["".join(a) for a in markup] f.writelines(markup) await client.send_message(chat_id, '文件已修改成功,原文件备份为' + path + '.bak') conv.cancel() return None, None, None, None elif os.path.isfile(path + '/' + res): msg = await client.edit_message(msg, '文件读取中...请稍候') with open(path + '/' + res, 'r', encoding='utf-8') as f: lines = f.readlines() lines = split_list(lines, 15) page = 0 return path + '/' + res, msg, page, lines else: return path + '/' + res, msg, page, None except exceptions.TimeoutError: msg = await client.edit_message(msg, '选择已超时,本次对话已停止') return None, None, None, None except Exception as e: msg = await client.edit_message( msg, 'something wrong,I\'m sorry\n' + str(e)) logger.error('something wrong,I\'m sorry\n' + str(e)) return None, None, None, None
async def inline_handler(event): builder = event.builder result = None query = event.text if event.query.user_id == bot.uid and query.startswith("`Userbot"): rev_text = query[::-1] buttons = paginate_help(0, CMD_LIST, "helpme") result = builder.article( "© hydra Help", text="{}\nCurrently Loaded Plugins: {}".format(query, len(CMD_LIST)), buttons=buttons, link_preview=False, ) elif event.query.user_id == bot.uid and query == "stats": result = builder.article( title="Stats", text=f"**hydra Stats For [{DEFAULTUSER}](tg://user?id={myid})**\n\n__Bot is functioning normally, master!__\n\n(c) @hydraSupport", buttons=[ [custom.Button.inline("Stats", data="statcheck")], [Button.url("Repo", "https://github.com/noob-kittu/HydraUserbot")], [ Button.url( "Deploy Now!", "https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.com%2Fnoob-kittu%2Fhydrauserbot&template=https%3A%2F%2Fgithub.com%2Fnoob-kittu%2Fhydrauserbot", ) ], ], ) elif event.query.user_id == bot.uid and query.startswith("**PM"): TELEBT = USER_BOT_NO_WARN.format(DEFAULTUSER, myid, MESAG) result = builder.photo( file=TELEPIC, text=TELEBT, buttons=[ [ custom.Button.inline("Request ", data="req"), custom.Button.inline("Chat 💭", data="chat"), ], [custom.Button.inline("To spam 🚫", data="heheboi")], [custom.Button.inline("What is this ❓", data="pmclick")], ], ) elif event.query.user_id == bot.uid and query == "repo": result = builder.article( title="Repository", text=f"Hydra - Telegram Userbot.", buttons=[ [ Button.url( "Repo", "https://github.com/noob-kittu/HydraUserbot" ), Button.url( "Deploy", "https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.com%2Fnoob-kittu%2FHydraUserbot&template=https%3A%2F%2Fgithub.com%2Fnoob-kittu%2FHydraUserbot", ), ], [Button.url("Support", "https://t.me/hydraSupport")], ], ) else: result = builder.article( "Source Code", text="**Welcome to hydra**\n\n`Click below buttons for more`", buttons=[ [custom.Button.url("Creator👨🦱", "https://t.me/yourkittu")], [ custom.Button.url( "👨💻Source Code💻", "https://github.com/noob-kittu/hydrauserbot", ), custom.Button.url( "Deploy 🌀", "https://dashboard.heroku.com/new?template=https%3A%2F%2Fgithub.com%2Fnoob-kittu%2Fhydrauserbot", ), ], [ custom.Button.url( "Updates and Support Group↗️", "https://t.me/hydraSupport" ) ], ], link_preview=False, ) await event.answer([result] if result else None)
async def _(event): ok = await datgbot(GetFullUserRequest(event.sender_id)) await event.reply(f"Hi `{ok.user.first_name}`!\n\nI am a channel auto-post bot!! Read /help to know more!\n\nI can be used in only two channels (one user) at a time. Kindly deploy your own bot.\n\n[More bots](https://t.me/darksideempire)..", buttons=[Button.url("Repo", url="https://t.me/darksideempire"), Button.url("Dev", url="https://t.me/darksideempire")], link_preview=False)
async def alv(event): await event.edit("Here are the avaialble customisations for PMSecurity", buttons=[[Button.inline("Message", data="pm_txt")], [Button.inline("Picture", data="pm_pic")]])
if not isinstance(webpage, types.WebPageEmpty) and webpage.type in [ "photo" ]: return webpage.display_url return event.text # --------------------------------------------------------------------# _buttons = { "otvars": { "text": "Other Variables to set for @TheUltroid:", "buttons": [ [ Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"), Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="cbs_sfban"), ], [ Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ", data="sudo"), Button.inline("Hᴀɴᴅʟᴇʀ", data="hhndlr"), ], [ Button.inline("Exᴛʀᴀ Pʟᴜɢɪɴs", data="plg"), Button.inline("Aᴅᴅᴏɴs", data="eaddon"), ], [ Button.inline("Eᴍᴏᴊɪ ɪɴ Hᴇʟᴘ", data="emoj"), Button.inline("Sᴇᴛ ɢDʀɪᴠᴇ", data="gdrive"), ], [
async def myqladdrepo(event): try: SENDER = event.sender_id if V4: btns = [ Button.inline("启动", data="start"), Button.inline("停止", data="stop"), Button.inline("删除", data="delete"), Button.inline("取消会话", data="cancel") ] else: btns = [ Button.inline("启用", data="enable"), Button.inline("禁用", data="disable"), Button.inline("删除", data="delete"), Button.inline("更新仓库", data="run"), Button.inline("取消会话", data="cancel") ] if V4: with open(_ConfigFile, 'r', encoding='utf-8') as f: configs = f.readlines() r_names, r_urls, r_namesline, r_branchs, r_branchsline, r_paths, r_pathsline, r_status, r_nums, btns_1 = [], [], [], [], [], [], [], [], [], [] for config in configs: if config.find("OwnRepoUrl") != -1 and config.find( "## ") == -1: url = config.split("=")[-1].replace('"', "") r_urls.append(url) reponum = re.findall(r"\d", config.split("=")[0])[0] r_nums.append(reponum) r_names.append(url.split("/")[-2]) r_namesline.append(configs.index(config)) if config.find("#") != -1: status = "禁用" else: status = "启用" r_status.append(status) elif config.find("OwnRepoBranch") != -1 and config.find( "## ") == -1: branch = config.split("=")[-1].replace('"', "") if branch == '': branch = "None" r_branchs.append(branch) r_branchsline.append(configs.index(config)) elif config.find("OwnRepoPath") != -1 and config.find( "## ") == -1: path = config.split("=")[-1].replace('"', "") if path == '': path = "None" r_paths.append(path) r_pathsline.append(configs.index(config)) elif config.find("启用其他开发者的仓库方式二") != -1: break for r_name in r_names: btns_1.append(Button.inline(r_name, data=r_name)) btns_1.append(Button.inline("更新全部仓库", data="jup own")) btns_1.append(Button.inline("取消会话", data="cancel")) async with jdbot.conversation(SENDER, timeout=60) as conv: msg = await conv.send_message("这是你目前添加的仓库", buttons=split_list(btns_1, row)) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await jdbot.edit_message(msg, '对话已取消,感谢你的使用') conv.cancel() return elif res == 'jup own': msg = await jdbot.edit_message(msg, '准备拉取全部仓库') os.system(res) conv.cancel() return i = r_names.index(res) name, url, branch, path, status, num = r_names[i], r_urls[ i], r_branchs[i], r_paths[i], r_status[i], r_nums[i] nameline, branchline, pathline = r_namesline[i], r_branchsline[ i], r_pathsline[i] data = f'仓库名:{name}\n仓库链接:{url}仓库分支:{branch}文件路径:{path}状态:{status}\n' msg = await jdbot.edit_message(msg, f'{data}请做出你的选择', buttons=split_list(btns, row)) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await jdbot.edit_message(msg, '对话已取消,感谢你的使用') conv.cancel() return elif res == 'start': await jdbot.edit_message(msg, "启动仓库") configs[nameline] = configs[nameline].replace("# ", "") configs[branchline] = configs[branchline].replace("# ", "") configs[pathline] = configs[pathline].replace("# ", "") configs = ''.join(configs) elif res == 'stop': await jdbot.edit_message(msg, "停止仓库") configs[nameline] = f"# {configs[nameline]}" configs[branchline] = f"# {configs[branchline]}" configs[pathline] = f"# {configs[pathline]}" configs = ''.join(configs) elif res == 'delete': await jdbot.edit_message(msg, "删除仓库") with open(_ConfigFile, 'r', encoding='utf-8') as f: configs = f.read() configs = re.sub(f"OwnRepoUrl{num}=.*", "", configs) configs = re.sub(f"OwnRepoBranch{num}=.*", "", configs) configs = re.sub(f"OwnRepoPath{num}=.*", "", configs) with open(_ConfigFile, 'w', encoding='utf-8') as f2: f2.write(configs) else: with open(_Auth, 'r', encoding='utf-8') as f: auth = json.load(f) token = auth['token'] url = 'http://127.0.0.1:5600/api/crons' body = { "searchValue": "ql repo", "t": int(round(time.time() * 1000)) } headers = {'Authorization': f'Bearer {token}'} resp = requests.get(url, params=body, headers=headers).json()['data'] datas, btns_1 = [], [] for data in resp: name = data['name'] command = data['command'] schedule = data['schedule'] status = '启用' _id = data['_id'] if data['status'] == 1: status = '禁用' datas.append([name, command, schedule, status, _id]) for _ in datas: i = datas.index(_) btns_1.append(Button.inline(_[0], data=f"{str(i)}")) btns_1.append(Button.inline("取消会话", data="cancel")) async with jdbot.conversation(SENDER, timeout=60) as conv: msg = await conv.send_message("这是你目前添加的仓库", buttons=split_list(btns_1, row)) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await jdbot.edit_message(msg, '对话已取消,感谢你的使用') conv.cancel() return data = datas[int(res)] info = f"任务名:{data[0]}\n命令:{data[1]}\n定时:{data[2]}\n状态:{data[3]}\n" msg = await jdbot.edit_message(msg, f"{info}请做出你的选择", buttons=split_list(btns, row)) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) _id = [data[4]] if res == 'cancel': msg = await jdbot.edit_message(msg, '对话已取消,感谢你的使用') conv.cancel() return elif res == 'delete': r = requests.delete( f"{url}?t={str(round(time.time() * 1000))}", json=_id, headers=headers).json() else: r = requests.put( f'{url}/{res}?t={str(round(time.time() * 1000))}', json=_id, headers=headers).json() conv.cancel() if r['code'] == 200: await jdbot.edit_message(msg, "操作成功") else: await jdbot.edit_message(msg, "操作失败,请手动尝试") except exceptions.TimeoutError: msg = await jdbot.edit_message(msg, '选择已超时,对话已停止,感谢你的使用') except Exception as e: await jdbot.send_message(chat_id, 'something wrong,I\'m sorry\n' + str(e)) logger.error('something wrong,I\'m sorry\n' + str(e))
async def ytdl_callback(c_q: CallbackQuery): choosen_btn = (str(c_q.pattern_match.group(1).decode("UTF-8")) if c_q.pattern_match.group(1) is not None else None) data_key = (str(c_q.pattern_match.group(2).decode("UTF-8")) if c_q.pattern_match.group(2) is not None else None) page = (str(c_q.pattern_match.group(3).decode("UTF-8")) if c_q.pattern_match.group(3) is not None else None) if not os.path.exists(PATH): return await c_q.answer( "Search data doesn't exists anymore, please perform search again ...", alert=True, ) with open(PATH) as f: view_data = ujson.load(f) search_data = view_data.get(data_key) total = len(search_data) if choosen_btn == "back": index = int(page) - 1 del_back = index == 1 await c_q.answer() back_vid = search_data.get(str(index)) await c_q.edit( text=back_vid.get("message"), file=await get_ytthumb(back_vid.get("video_id")), buttons=yt_search_btns( del_back=del_back, data_key=data_key, page=index, vid=back_vid.get("video_id"), total=total, ), parse_mode="html", ) elif choosen_btn == "next": index = int(page) + 1 if index > total: return await c_q.answer("That's All Folks !", alert=True) await c_q.answer() front_vid = search_data.get(str(index)) await c_q.edit( text=front_vid.get("message"), file=await get_ytthumb(front_vid.get("video_id")), buttons=yt_search_btns( data_key=data_key, page=index, vid=front_vid.get("video_id"), total=total, ), parse_mode="html", ) elif choosen_btn == "listall": await c_q.answer("View Changed to: 📜 List", alert=False) list_res = "".join( search_data.get(vid_s).get("list_view") for vid_s in search_data) telegraph = await post_to_telegraph( f"Showing {total} youtube video results for the given query ...", list_res, ) await c_q.edit( file=await get_ytthumb(search_data.get("1").get("video_id")), buttons=[ (Button.url( "↗️ Click To Open", url=telegraph, )), (Button.inline( "📰 Detailed View", data=f"ytdl_detail_{data_key}_{page}", )), ], ) else: # Detailed index = 1 await c_q.answer("View Changed to: 📰 Detailed", alert=False) first = search_data.get(str(index)) await c_q.edit( text=first.get("message"), file=await get_ytthumb(first.get("video_id")), buttons=yt_search_btns( del_back=True, data_key=data_key, page=index, vid=first.get("video_id"), total=total, ), parse_mode="html", )
async def settings(event): await event.delete() await tgbot.send_message( event.chat_id, f"This is the personal help bot of {THEFIRST_NAME}.", buttons=[[Button.inline("Deploy me for yourself", data="deployme")]])
async def myaddrepo(event): try: SENDER = event.sender_id url = event.raw_text short_url, git_name = url.split('/')[-1].replace( ".git", ""), url.split("/")[-2] btns_yn = [ Button.inline("是", data="yes"), Button.inline("否", data="no") ] if V4: tips_1 = [ f'正在设置 OwnRepoBranch(分支) 的值\n该值为你想使用脚本在[仓库]({url})的哪个分支', '正在设置 OwnRepoPath(路径) 的值\n该值为你要使用的脚本在分支的哪个路径' ] tips_2 = [ f'回复 main 代表使用 [{short_url}]({url}) 仓库的 "main" 分支\n回复 master 代表使用 [{short_url}]({url}) 仓库的 "master" 分支\n具体分支名称以你所发仓库实际为准\n', f'回复 scripts/jd normal 代表你想使用的脚本在 [{short_url}]({url}) 仓库的 scripts/jd 和 normal文件夹下\n回复 root cron 代表你想使用的脚本在 [{short_url}]({url}) 仓库的 根目录 和 cron 文件夹下\n具体目录路径以你所发仓库实际为准\n' ] tips_3 = [[ Button.inline('"默认" 分支', data='root'), Button.inline('"main" 分支', data='main'), Button.inline('"master" 分支', data='master'), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ], [ Button.inline('仓库根目录', data='root'), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ]] else: tips_1 = [ f'正在设置 branch(分支) 的值\n该值为你想使用脚本在[仓库]({url})的哪个分支', f'正在设置 path(路径) 的值\n该值为你要使用的脚本在分支的哪个路径\n或你要使用根目录下哪些名字开头的脚本(可用空格或|隔开)', f'正在设置 blacklist(黑名单) 的值\n该值为你不需要使用以哪些名字开头的脚本(可用空格或|隔开)', f'正在设置 dependence(依赖文件) 的值\n该值为你想使用的依赖文件名称', f'正在设置定时拉取仓库的 cron 表达式,可默认每日 0 点' ] tips_2 = [ f'回复 main 代表使用 [{short_url}]({url}) 仓库的 "main" 分支\n回复 master 代表使用 [{short_url}]({url}) 仓库的 "master" 分支\n具体分支名称以你所发仓库实际为准\n', f'回复 scripts normal 代表你想使用的脚本在 [{short_url}]({url}) 仓库的 scripts 和 normal文件夹下\n具体目录路径以你所发仓库实际为准\n', f'回复 jd_ jx_ 代表你不想使用开头为 jd_ 和 jx_ 的脚本\n具体文件名以你所发仓库实际、以你个人所需为准\n', f'回复你所需要安装依赖的文件全称\n具体文件名以你所发仓库实际、以你个人所需为准\n', f"回复你所需设置的 cron 表达式" ] tips_3 = [[ Button.inline('"默认" 分支', data='root'), Button.inline('"main" 分支', data='main'), Button.inline('"master" 分支', data='master'), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ], [ Button.inline('仓库根目录', data='root'), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ], [ Button.inline("不设置", data="root"), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ], [ Button.inline("不设置", data="root"), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ], [ Button.inline("默认每天0点", data="root"), Button.inline('手动输入', data='input'), Button.inline('取消对话', data='cancel') ]] replies = [] async with jdbot.conversation(SENDER, timeout=60) as conv: for tip_1 in tips_1: i = tips_1.index(tip_1) msg = await conv.send_message(tip_1, buttons=split_list( tips_3[i], row)) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await jdbot.edit_message(msg, '对话已取消,感谢你的使用') conv.cancel() return elif res == 'input': await jdbot.delete_messages(chat_id, msg) msg = await conv.send_message(tips_2[i]) reply = await conv.get_response() res = reply.raw_text replies.append(res) await jdbot.delete_messages(chat_id, msg) conv.cancel() if V4: nums = [] with open(_ConfigFile, 'r', encoding='utf-8') as f1: configs = f1.readlines() for config in configs: if config.find('启用其他开发者的仓库方式一') != -1: start_line = configs.index(config) elif config.find('OwnRepoUrl1=""') != -1 and config.find( "## ") == -1: nums = [1] break elif config.find('OwnRepoUrl2=""') != -1 and config.find( "## ") == -1: nums = [2] break elif config.find('OwnRepoUrl') != -1 and config.find( "## ") == -1: num = int( re.findall(r'(?<=OwnRepoUrl)[\d]+(?==")', config)[0]) nums.append(num) elif config.find('启用其他开发者的仓库方式二') != -1: end_line = configs.index(config) break nums.sort() OwnRepoUrl = f'OwnRepoUrl{nums[-1] + 1}="{url}"\n' OwnRepoBranch = f'OwnRepoBranch{nums[-1] + 1}="{replies[0].replace("root", "")}"\n' Path = replies[1].replace("root", "''") if Path == "''": OwnRepoPath = f'OwnRepoPath{nums[-1] + 1}=""\n' else: OwnRepoPath = f'OwnRepoPath{nums[-1] + 1}="{Path}"\n' for config in configs[start_line:end_line]: if config.find(f'OwnRepoUrl{nums[-1]}') != -1 and config.find( "## ") == -1: configs.insert(configs.index(config) + 1, OwnRepoUrl) elif config.find(f'OwnRepoBranch{nums[-1]}' ) != -1 and config.find("## ") == -1: configs.insert(configs.index(config) + 1, OwnRepoBranch) elif config.find(f'OwnRepoPath{nums[-1]}' ) != -1 and config.find("## ") == -1: configs.insert(configs.index(config) + 1, OwnRepoPath) with open(_ConfigFile, 'w', encoding='utf-8') as f2: f2.write(''.join(configs)) await jdbot.send_message(chat_id, "现在开始拉取仓库,稍后请自行查看结果") os.system("jup own") else: branch = replies[0].replace("root", "") path = replies[1].replace(" ", "|").replace("root", "") blacklist = replies[2].replace(" ", "|").replace("root", "") dependence = replies[3].replace("root", "") cron = replies[4].replace("root", "0 0 * * *") cmdtext = f'ql repo {url} "{path}" "{blacklist}" "{dependence}" "{branch}"' res = myqladdrepo2(git_name, cmdtext, cron) await jdbot.send_message(chat_id, f"现在开始拉取仓库,稍后请自行查看结果") await cmd(cmdtext) except exceptions.TimeoutError: msg = await jdbot.edit_message(msg, '选择已超时,对话已停止,感谢你的使用') except Exception as e: await jdbot.send_message(chat_id, 'something wrong,I\'m sorry\n' + str(e)) logger.error('something wrong,I\'m sorry\n' + str(e))
async def start(event): await event.reply( "HELLO VMRO!!\n𝙸'𝙼 𝙿𝙴𝚁𝚂𝙾𝙽𝙰𝙻 𝙰𝚂𝚂𝙸𝚂𝚃𝙰𝙽𝚃 𝙾𝙵 @ShashankxD \n𝙿𝚁𝙴𝚂𝚂 𝚃𝙷𝙴 𝙱𝙴𝙻𝙾𝚆 𝙱𝚄𝚃𝚃𝙾𝙽 𝚃𝙾 𝙺𝙽𝙾𝚆 𝙼𝙾𝚁𝙴 𝙰𝙱𝙾𝚄𝚃 𝚂𝙷𝙰𝚂𝙷𝙰𝙽𝙺", buttons=[[Button.inline("𝙼𝚢 𝚌𝚛𝚎𝚊𝚝𝚘𝚛", data="Creator")], [Button.inline("𝚃𝙴𝙰𝙼 𝙲𝙾𝙵𝙵𝙸𝙽", data="TeamCoffin")]])
async def soon(event): buttons = [ Button.inline("Go Back", data="soon"), ] await event.edit(about, buttons=buttons)
async def on_snip(event): global last_triggered_filters name = event.raw_text if event.chat_id in last_triggered_filters: if name in last_triggered_filters[event.chat_id]: return False snips = get_all_filters(event.chat_id) if snips: for snip in snips: pattern = r"( |^|[^\w])" + re.escape(snip.keyword) + r"( |$|[^\w])" if re.search(pattern, name, flags=re.IGNORECASE): if snip.snip_type == TYPE_PHOTO: media = types.InputPhoto( int(snip.media_id), int(snip.media_access_hash), snip.media_file_reference, ) elif snip.snip_type == TYPE_DOCUMENT: media = types.InputDocument( int(snip.media_id), int(snip.media_access_hash), snip.media_file_reference, ) else: media = None event.message.id if event.reply_to_msg_id: event.reply_to_msg_id filter = "" options = "" butto = None if "|" in snip.reply: filter, options = snip.reply.split("|") else: filter = str(snip.reply) try: filter = filter.strip() button = options.strip() params = re.findall(r'\'(.*?)\'', button) butto = [Button.url(*params)] except BaseException: filter = filter.strip() button = None await event.reply(filter, buttons=butto, file=media) if event.chat_id not in last_triggered_filters: last_triggered_filters[event.chat_id] = [] last_triggered_filters[event.chat_id].append(name) await asyncio.sleep(DELETE_TIMEOUT) last_triggered_filters[event.chat_id].remove(name)
async def custommm(event): await event.edit("Modules which you can customise -", buttons=[[Button.inline("Alive", data="alive_cus")], [Button.inline("PMSecurity", data="pm_cus")]])
async def inline_handler(event): # sourcery no-metrics builder = event.builder result = None query = event.text string = query.lower() query.split(" ", 2) str_y = query.split(" ", 1) string.split() query_user_id = event.query.user_id if query_user_id == Config.OWNER_ID or query_user_id in Config.SUDO_USERS: hmm = re.compile("troll (.*) (.*)") match = re.findall(hmm, query) inf = re.compile("secret (.*) (.*)") match2 = re.findall(inf, query) hid = re.compile("hide (.*)") match3 = re.findall(hid, query) if query.startswith("**Catuserbot"): buttons = [( Button.inline("Stats", data="stats"), Button.url("Repo", "https://github.com/TgCatUB/catuserbot"), )] ALIVE_PIC = gvarstatus("ALIVE_PIC") IALIVE_PIC = gvarstatus("IALIVE_PIC") if IALIVE_PIC: CAT = [x for x in IALIVE_PIC.split()] PIC = list(CAT) I_IMG = random.choice(PIC) if not IALIVE_PIC and ALIVE_PIC: CAT = [x for x in ALIVE_PIC.split()] PIC = list(CAT) I_IMG = random.choice(PIC) elif not IALIVE_PIC: I_IMG = None if I_IMG and I_IMG.endswith((".jpg", ".png")): result = builder.photo( I_IMG, text=query, buttons=buttons, ) elif I_IMG: result = builder.document( I_IMG, title="Alive cat", text=query, buttons=buttons, ) else: result = builder.article( title="Alive cat", text=query, buttons=buttons, ) await event.answer([result] if result else None) elif query.startswith("Inline buttons"): markdown_note = query[14:] prev = 0 note_data = "" buttons = [] for match in BTN_URL_REGEX.finditer(markdown_note): n_escapes = 0 to_check = match.start(1) - 1 while to_check > 0 and markdown_note[to_check] == "\\": n_escapes += 1 to_check -= 1 if n_escapes % 2 == 0: buttons.append( (match.group(2), match.group(3), bool(match.group(4)))) note_data += markdown_note[prev:match.start(1)] prev = match.end(1) elif n_escapes % 2 == 1: note_data += markdown_note[prev:to_check] prev = match.start(1) - 1 else: break else: note_data += markdown_note[prev:] message_text = note_data.strip() tl_ib_buttons = ibuild_keyboard(buttons) result = builder.article( title="Inline creator", text=message_text, buttons=tl_ib_buttons, link_preview=False, ) await event.answer([result] if result else None) elif match: query = query[7:] user, txct = query.split(" ", 1) builder = event.builder troll = os.path.join("./userbot", "troll.txt") try: jsondata = json.load(open(troll)) except Exception: jsondata = False try: # if u is user id u = int(user) try: u = await event.client.get_entity(u) if u.username: sandy = f"@{u.username}" else: sandy = f"[{u.first_name}](tg://user?id={u.id})" u = int(u.id) except ValueError: # ValueError: Could not find the input entity sandy = f"[user](tg://user?id={u})" except ValueError: # if u is username try: u = await event.client.get_entity(user) except ValueError: return if u.username: sandy = f"@{u.username}" else: sandy = f"[{u.first_name}](tg://user?id={u.id})" u = int(u.id) except Exception: return timestamp = int(time.time() * 2) newtroll = {str(timestamp): {"userid": u, "text": txct}} buttons = [ Button.inline("show message 🔐", data=f"troll_{timestamp}") ] result = builder.article( title="Troll Message", text=f"Only {sandy} cannot access this message!", buttons=buttons, ) await event.answer([result] if result else None) if jsondata: jsondata.update(newtroll) json.dump(jsondata, open(troll, "w")) else: json.dump(newtroll, open(troll, "w")) elif match2: query = query[7:] user, txct = query.split(" ", 1) builder = event.builder secret = os.path.join("./userbot", "secrets.txt") try: jsondata = json.load(open(secret)) except Exception: jsondata = False try: # if u is user id u = int(user) try: u = await event.client.get_entity(u) if u.username: sandy = f"@{u.username}" else: sandy = f"[{u.first_name}](tg://user?id={u.id})" u = int(u.id) except ValueError: # ValueError: Could not find the input entity sandy = f"[user](tg://user?id={u})" except ValueError: # if u is username try: u = await event.client.get_entity(user) except ValueError: return if u.username: sandy = f"@{u.username}" else: sandy = f"[{u.first_name}](tg://user?id={u.id})" u = int(u.id) except Exception: return timestamp = int(time.time() * 2) newsecret = {str(timestamp): {"userid": u, "text": txct}} buttons = [ Button.inline("show message 🔐", data=f"secret_{timestamp}") ] result = builder.article( title="secret message", text= f"🔒 A whisper message to {sandy}, Only he/she can open it.", buttons=buttons, ) await event.answer([result] if result else None) if jsondata: jsondata.update(newsecret) json.dump(jsondata, open(secret, "w")) else: json.dump(newsecret, open(secret, "w")) elif match3: query = query[5:] builder = event.builder hide = os.path.join("./userbot", "hide.txt") try: jsondata = json.load(open(hide)) except Exception: jsondata = False timestamp = int(time.time() * 2) newhide = {str(timestamp): {"text": query}} buttons = [ Button.inline("Read Message ", data=f"hide_{timestamp}") ] result = builder.article( title="Hidden Message", text=f"✖✖✖", buttons=buttons, ) await event.answer([result] if result else None) if jsondata: jsondata.update(newhide) json.dump(jsondata, open(hide, "w")) else: json.dump(newhide, open(hide, "w")) elif string == "help": _result = main_menu() result = builder.article( title="© CatUserbot Help", description="Help menu for CatUserbot", text=_result[0], buttons=_result[1], link_preview=False, ) await event.answer([result] if result else None) elif str_y[0].lower() == "ytdl" and len(str_y) == 2: link = get_yt_video_id(str_y[1].strip()) found_ = True if link is None: search = VideosSearch(str_y[1].strip(), limit=15) resp = (search.result()).get("result") if len(resp) == 0: found_ = False else: outdata = await result_formatter(resp) key_ = rand_key() ytsearch_data.store_(key_, outdata) buttons = [ Button.inline( f"1 / {len(outdata)}", data=f"ytdl_next_{key_}_1", ), Button.inline( "📜 List all", data=f"ytdl_listall_{key_}_1", ), Button.inline( "⬇️ Download", data=f'ytdl_download_{outdata[1]["video_id"]}_0', ), ] caption = outdata[1]["message"] photo = await get_ytthumb(outdata[1]["video_id"]) else: caption, buttons = await download_button(link, body=True) photo = await get_ytthumb(link) if found_: markup = event.client.build_reply_markup(buttons) photo = types.InputWebDocument(url=photo, size=0, mime_type="image/jpeg", attributes=[]) text, msg_entities = await event.client._parse_message_text( caption, "html") result = types.InputBotInlineResult( id=str(uuid4()), type="photo", title=link, description="⬇️ Click to Download", thumb=photo, content=photo, send_message=types.InputBotInlineMessageMediaAuto( reply_markup=markup, message=text, entities=msg_entities), ) else: result = builder.article( title="Not Found", text=f"No Results found for `{str_y[1]}`", description="INVALID", ) try: await event.answer([result] if result else None) except QueryIdInvalidError: await event.answer([ builder.article( title="Not Found", text=f"No Results found for `{str_y[1]}`", description="INVALID", ) ]) elif string == "age_verification_alert": buttons = [ Button.inline(text="Yes I'm 18+", data="age_verification_true"), Button.inline(text="No I'm Not", data="age_verification_false"), ] markup = event.client.build_reply_markup(buttons) photo = types.InputWebDocument( url="https://i.imgur.com/Zg58iXc.jpg", size=0, mime_type="image/jpeg", attributes=[], ) text, msg_entities = await event.client._parse_message_text( "<b>ARE YOU OLD ENOUGH FOR THIS ?</b>", "html") result = types.InputBotInlineResult( id=str(uuid4()), type="photo", title="Age verification", thumb=photo, content=photo, send_message=types.InputBotInlineMessageMediaAuto( reply_markup=markup, message=text, entities=msg_entities), ) await event.answer([result] if result else None) elif string == "pmpermit": buttons = [ Button.inline(text="Show Options.", data="show_pmpermit_options"), ] PM_PIC = gvarstatus("pmpermit_pic") if PM_PIC: CAT = [x for x in PM_PIC.split()] PIC = list(CAT) CAT_IMG = random.choice(PIC) else: CAT_IMG = None query = gvarstatus("pmpermit_text") if CAT_IMG and CAT_IMG.endswith((".jpg", ".jpeg", ".png")): result = builder.photo( CAT_IMG, # title="Alive cat", text=query, buttons=buttons, ) elif CAT_IMG: result = builder.document( CAT_IMG, title="Alive cat", text=query, buttons=buttons, ) else: result = builder.article( title="Alive cat", text=query, buttons=buttons, ) await event.answer([result] if result else None) else: buttons = [( Button.url("Source code", "https://github.com/TgCatUB/catuserbot"), Button.url( "Deploy", "https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.com%2FMr-confused%2Fcatpack&template=https%3A%2F%2Fgithub.com%2FMr-confused%2Fcatpack", ), )] markup = event.client.build_reply_markup(buttons) photo = types.InputWebDocument(url=CATLOGO, size=0, mime_type="image/jpeg", attributes=[]) text, msg_entities = await event.client._parse_message_text( "𝗗𝗲𝗽𝗹𝗼𝘆 𝘆𝗼𝘂𝗿 𝗼𝘄𝗻 𝗖𝗮𝘁𝗨𝘀𝗲𝗿𝗯𝗼𝘁.", "md") result = types.InputBotInlineResult( id=str(uuid4()), type="photo", title="𝘾𝙖𝙩𝙐𝙨𝙚𝙧𝙗𝙤𝙩", description="Deploy yourself", url="https://github.com/TgCatUB/catuserbot", thumb=photo, content=photo, send_message=types.InputBotInlineMessageMediaAuto( reply_markup=markup, message=text, entities=msg_entities), ) await event.answer([result] if result else None)
async def alv(event): await event.edit("Here are the avaialble customisations for alive", buttons=[[Button.inline("Text", data="alv_txt")], [Button.inline("Picture", data="alv_pic")]])
async def on_plug_in_callback_query_handler(event): buttons = [ (Button.inline("Open Menu", data="mainmenu"), ), ] await event.edit("Menu Closed", buttons=buttons)
async def dev(kimo): await kimo.reply("⌔∮ 𝙎𝙊𝙐𝙍𝘾𝙀 𝙄𝘾𝙎𝙎 - 𝙍𝙀𝙋𝙊 𓆪", buttons=[[Button.url("🔗 𝙍𝙀𝙋𝙊 🔗", K)]])
def paginate_help( page_number, loaded_plugins, prefix, plugins=True, category_plugins=None, category_pgno=0, ): # sourcery no-metrics try: number_of_rows = int(gvarstatus("NO_OF_ROWS_IN_HELP") or 5) except (ValueError, TypeError): number_of_rows = 5 try: number_of_cols = int(gvarstatus("NO_OF_COLUMNS_IN_HELP") or 2) except (ValueError, TypeError): number_of_cols = 2 HELP_EMOJI = gvarstatus("HELP_EMOJI") or " " helpable_plugins = [p for p in loaded_plugins if not p.startswith("_")] helpable_plugins = sorted(helpable_plugins) if len(HELP_EMOJI) == 2: if plugins: modules = [ Button.inline( f"{HELP_EMOJI[0]} {x} {HELP_EMOJI[1]}", data=f"{x}_prev(1)_command_{prefix}_{page_number}", ) for x in helpable_plugins ] else: modules = [ Button.inline( f"{HELP_EMOJI[0]} {x} {HELP_EMOJI[1]}", data= f"{x}_cmdhelp_{prefix}_{page_number}_{category_plugins}_{category_pgno}", ) for x in helpable_plugins ] elif plugins: modules = [ Button.inline( f"{HELP_EMOJI} {x} {HELP_EMOJI}", data=f"{x}_prev(1)_command_{prefix}_{page_number}", ) for x in helpable_plugins ] else: modules = [ Button.inline( f"{HELP_EMOJI} {x} {HELP_EMOJI}", data= f"{x}_cmdhelp_{prefix}_{page_number}_{category_plugins}_{category_pgno}", ) for x in helpable_plugins ] if number_of_cols == 1: pairs = list(zip(modules[::number_of_cols])) elif number_of_cols == 2: pairs = list(zip(modules[::number_of_cols], modules[1::number_of_cols])) else: pairs = list( zip( modules[::number_of_cols], modules[1::number_of_cols], modules[2::number_of_cols], )) if len(modules) % number_of_cols == 1: pairs.append((modules[-1], )) elif len(modules) % number_of_cols == 2: pairs.append((modules[-2], modules[-1])) max_num_pages = math.ceil(len(pairs) / number_of_rows) modulo_page = page_number % max_num_pages if plugins: if len(pairs) > number_of_rows: pairs = pairs[modulo_page * number_of_rows:number_of_rows * (modulo_page + 1)] + [( Button.inline( "⌫", data=f"{prefix}_prev({modulo_page})_plugin"), Button.inline("⚙️ Main Menu", data="mainmenu"), Button.inline( "⌦", data=f"{prefix}_next({modulo_page})_plugin"), )] else: pairs = pairs + [(Button.inline("⚙️ Main Menu", data="mainmenu"), ) ] elif len(pairs) > number_of_rows: if category_pgno < 0: category_pgno = len(pairs) + category_pgno pairs = pairs[modulo_page * number_of_rows:number_of_rows * ( modulo_page + 1 )] + [( Button.inline( "⌫", data= f"{prefix}_prev({modulo_page})_command_{category_plugins}_{category_pgno}", ), Button.inline( "⬅️ Back ", data=f"back_plugin_{category_plugins}_{category_pgno}", ), Button.inline( "⌦", data= f"{prefix}_next({modulo_page})_command_{category_plugins}_{category_pgno}", ), )] else: if category_pgno < 0: category_pgno = len(pairs) + category_pgno pairs = pairs + [(Button.inline( "⬅️ Back ", data=f"back_plugin_{category_plugins}_{category_pgno}", ), )] return pairs
async def pmlog(event): await setit(event, "PMLOG", "True") await event.edit( "Done!! PMLOGGER Started!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]], )
async def render(self) -> tuple[str, Optional[list]]: if not len(self.scored_documents): return t('COULD_NOT_FIND_ANYTHING', language=self.chat.language), [ close_button(self.session_id) ] serp_elements = [] bot_external_name = self.application.config['telegram'][ 'bot_external_name'] for scored_document in self.scored_documents: view = parse_typed_document_to_view(scored_document.typed_document) if not self.is_group_mode: view_command = view.get_view_command( session_id=self.session_id, message_id=self.message_id, position=scored_document.position, ) else: view_command = view.get_deep_link(bot_external_name, text='⬇️') serp_elements.append( view.get_snippet( language=self.chat.language, view_command=view_command, limit=512 + 128, )) serp = '\n\n'.join(serp_elements) if self.is_group_mode: try: encoded_query = encode_query_to_deep_link( self.query, bot_external_name, ) serp = ( f"{serp}\n\n**{t('DOWNLOAD_AND_SEARCH_MORE', language=self.chat.language)}: **" f'[@{bot_external_name}]' f'({encoded_query})') except TooLongQueryError: serp = ( f"{serp}\n\n**{t('DOWNLOAD_AND_SEARCH_MORE', language=self.chat.language)}: **" f'[@{bot_external_name}]' f'(https://t.me/{bot_external_name})') if not self.is_group_mode: promo = self.application.promotioner.choose_promotion( language=self.chat.language).format( related_channel=self.application.config['telegram'] ['related_channel'], ) serp = f'{serp}\n\n{promo}\n' buttons = None if not self.is_group_mode: buttons = [] if self.has_next or self.page > 0: buttons = [ Button.inline( text='<<1' if self.page > 1 else ' ', data=f'/search_{self.session_id}_{self.message_id}_0' if self.page > 1 else '/noop', ), Button.inline( text=f'<{self.page}' if self.page > 0 else ' ', data= f'/search_{self.session_id}_{self.message_id}_{self.page - 1}' if self.page > 0 else '/noop', ), Button.inline( text=f'{self.page + 2}>' if self.has_next else ' ', data= f'/search_{self.session_id}_{self.message_id}_{self.page + 1}' if self.has_next else '/noop', ) ] buttons.append(close_button(self.session_id)) return serp, buttons
async def handler(event): if not await is_sudo(event): await event.respond( "You are not authorized to use this Bot. Create your own.") return if "1" in status: await event.respond("A task is already running.") return if "2" in status: await event.respond("Sleeping the engine for avoiding ban.") return async with bot.conversation(event.chat_id) as conv: await conv.send_message( "Please send the channel id from where you want to forward messages as a reply to this message." ) while True: r = conv.wait_event(events.NewMessage(chats=event.chat_id)) r = await r global fromchannel fromchannel = r.message.message.strip() if not r.is_reply: await conv.send_message( "Please send the message as a reply to the message.") else: await conv.send_message( "Okay now send me the channel id to where you want to forward messages as a reply to this message." ) break while True: p = conv.wait_event(events.NewMessage(chats=event.chat_id)) p = await p global tochannel tochannel = p.message.message.strip() if not p.is_reply: await conv.send_message( "Please send the message as a reply to the message.") else: await conv.send_message( "Okay now send me the message id from where you want to start forwarding as a reply to this message.(0 if you want to forward from begining)" ) break while True: q = conv.wait_event(events.NewMessage(chats=event.chat_id)) q = await q global offsetid offsetid = q.message.message.strip() if not q.is_reply: await conv.send_message( "Please send the message as a reply to the message.") else: break await event.respond('Select What you need to forward', buttons=[[ Button.inline('All Messages', b'all'), Button.inline('Only Photos', b'photo') ], [ Button.inline('Only Documents', b'docs'), Button.inline(' Only Video', b'video') ]])
"Попытка подключения клиента без прокси.") bot = TelegramClient(app_name, app_api_id, app_api_hash).start( bot_token=bot_token ) else: proxy = (proxy_server, int(proxy_port), proxy_key) bot = TelegramClient(app_name, app_api_id, app_api_hash, connection=connection.ConnectionTcpMTProxyRandomizedIntermediate, proxy=proxy).start(bot_token=bot_token) # флаг режима администратора flag_admin = False # кнопки главного режима для администратора button_main_admin = [ [Button.text("/help"), Button.text("/admin"), Button.text("/settings")] ] # кнопки главного режима для обычного пользователя button_main_user = [ [Button.text("/help"), Button.text("/admin")] ] # кнопки для режима администратора button_admin = [ [Button.text("/AddUser"), Button.text("/DelUser"), Button.text("/InfoUser"),
async def inline_handler(event): builder = event.builder result = None query = event.text hmm = re.compile("secret (.*) (.*)") match = re.findall(hmm, query) if query.startswith( "**IcssUserbot") and event.query.user_id == bot.uid: buttons = [( custom.Button.inline("Stats", data="stats"), Button.url("Repo", "https://github.com/ANL0KE/ICSS"), )] if CAT_IMG and CAT_IMG.endswith((".jpg", ".png")): result = builder.photo( CAT_IMG, # title="Alive cat", text=query, buttons=buttons, ) elif CAT_IMG: result = builder.document( CAT_IMG, title="Alive cat", text=query, buttons=buttons, ) else: result = builder.article( title="Alive cat", text=query, buttons=buttons, ) await event.answer([result] if result else None) elif event.query.user_id == bot.uid and query.startswith("Userbot"): rev_text = query[::-1] buttons = paginate_help(0, CMD_LIST, "helpme") result = builder.article( "© Userbot Help", text="{}\n⌔∮ Plugins: {}".format(query, len(CMD_LIST)), buttons=buttons, link_preview=False, ) await event.answer([result] if result else None) elif event.query.user_id == bot.uid and query.startswith( "Inline buttons"): markdown_note = query[14:] prev = 0 note_data = "" buttons = [] for match in BTN_URL_REGEX.finditer(markdown_note): # Check if btnurl is escaped n_escapes = 0 to_check = match.start(1) - 1 while to_check > 0 and markdown_note[to_check] == "\\": n_escapes += 1 to_check -= 1 # if even, not escaped -> create button if n_escapes % 2 == 0: # create a thruple with button label, url, and newline # status buttons.append( (match.group(2), match.group(3), bool(match.group(4)))) note_data += markdown_note[prev:match.start(1)] prev = match.end(1) # if odd, escaped -> move along elif n_escapes % 2 == 1: note_data += markdown_note[prev:to_check] prev = match.start(1) - 1 else: break else: note_data += markdown_note[prev:] message_text = note_data.strip() tl_ib_buttons = ibuild_keyboard(buttons) result = builder.article( title="Inline creator", text=message_text, buttons=tl_ib_buttons, link_preview=False, ) await event.answer([result] if result else None) elif event.query.user_id == bot.uid and match: query = query[7:] user, txct = query.split(" ", 1) builder = event.builder secret = os.path.join("./userbot", "secrets.txt") try: jsondata = json.load(open(secret)) except Exception: jsondata = False try: # if u is user id u = int(user) try: u = await event.client.get_entity(u) if u.username: sandy = f"@{u.username}" else: sandy = f"[{u.first_name}](tg://user?id={u.id})" except ValueError: # ValueError: Could not find the input entity sandy = f"[user](tg://user?id={u})" except ValueError: # if u is username try: u = await event.client.get_entity(user) except ValueError: return if u.username: sandy = f"@{u.username}" else: sandy = f"[{u.first_name}](tg://user?id={u.id})" u = int(u.id) except Exception: return timestamp = int(time.time() * 2) newsecret = {str(timestamp): {"userid": u, "text": txct}} buttons = [ custom.Button.inline("show message 🔐", data=f"secret_{timestamp}") ] result = builder.article( title="secret message", text= f"🔒 A whisper message to {sandy}, Only he/she can open it.", buttons=buttons, ) await event.answer([result] if result else None) if jsondata: jsondata.update(newsecret) json.dump(jsondata, open(secret, "w")) else: json.dump(newsecret, open(secret, "w"))
async def settings(event): await event.delete() await tgbot.send_message( event.chat_id, "There isn't much that you can do over here rn.", buttons=[[Button.inline("Deploy me for yourself", data="deployme")]])
async def nodebtn(conv, SENDER, path, msg, page, filelist): '''定义scripts脚本按钮''' mybtn = [ Button.inline('上一页', data='up'), Button.inline('下一页', data='next'), Button.inline('上级', data='updir'), Button.inline('取消', data='cancel') ] try: if filelist: markup = filelist newmarkup = markup[page] if mybtn not in newmarkup: newmarkup.append(mybtn) else: if path == _JdDir: dir = ['scripts', 'diyscripts'] else: dir = os.listdir(path) dir = await getname(path, dir) dir.sort() markup = [ Button.inline(file.split('--->')[0], data=str(file.split('--->')[-1])) for file in dir if os.path.isdir(path + '/' + file) or re.search(r'.js$', file.split('--->')[-1]) ] markup = split_list(markup, 3) if len(markup) > 30: markup = split_list(markup, 30) newmarkup = markup[page] newmarkup.append(mybtn) else: newmarkup = markup if path == _JdDir: newmarkup.append([Button.inline('取消', data='cancel')]) else: newmarkup.append([ Button.inline('上级', data='updir'), Button.inline('取消', data='cancel') ]) msg = await client.edit_message(msg, '请做出您的选择:', buttons=newmarkup) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': msg = await client.edit_message(msg, '对话已取消') conv.cancel() return None, None, None elif res == 'next': page = page + 1 if page > len(markup) - 1: page = 0 return path, msg, page, markup elif res == 'up': page = page - 1 if page < 0: page = len(markup) - 1 return path, msg, page, markup elif res == 'updir': path = '/'.join(path.split('/')[:-1]) if path == '': path = _JdDir return path, msg, page, None elif os.path.isfile(path + '/' + res): msg = await client.edit_message(msg, '脚本即将在后台运行') logger.info(path + '/' + res + '脚本即将在后台运行') cmdtext = 'js {} now'.format(res) subprocess.Popen(cmdtext, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) msg = await client.edit_message(msg, res + '在后台运行成功,请自行在程序结束后查看日志') conv.cancel() return None, None, None, None else: return path + '/' + res, msg, page, None except exceptions.TimeoutError: msg = await client.edit_message(msg, '选择已超时,对话已停止') return None, None, None, None except Exception as e: msg = await client.edit_message( msg, 'something wrong,I\'m sorry\n' + str(e)) logger.error('something wrong,I\'m sorry\n' + str(e)) return None, None, None, None
async def settings(event): await event.delete() await tgbot.send_message( event.chat_id, f"This is the personal help bot of {TELE_NAME}. You can contact me using this bot if necessary, or if I missed out your PM.", buttons=[[Button.inline("Deploy me for yourself", data="deployme")]])
async def mycookie(event): '''接收/getcookie后执行程序''' login = True msg = await client.send_message(chat_id, '正在获取二维码,请稍后') global cookiemsg try: SENDER = event.sender_id async with client.conversation(SENDER, timeout=30) as conv: getSToken() getOKLToken() url = 'https://plogin.m.jd.com/cgi-bin/m/tmauth?appid=300&client_type=m&token=' + token creatqr(url) markup = [ Button.inline("已扫码", data='confirm'), Button.inline("取消", data='cancel') ] await client.delete_messages(chat_id, msg) cookiemsg = await client.send_message( chat_id, '30s内点击取消将取消本次操作\n如不取消,扫码结果将于30s后显示\n扫码后不想等待点击已扫码', file=img_file, buttons=markup) convdata = await conv.wait_event(press_event(SENDER)) res = bytes.decode(convdata.data) if res == 'cancel': login = False await client.delete_messages(chat_id, cookiemsg) msg = await conv.send_message('对话已取消') conv.cancel() else: raise exceptions.TimeoutError() except exceptions.TimeoutError: expired_time = time.time() + 60 * 2 while login: check_time_stamp = int(time.time() * 1000) check_url = 'https://plogin.m.jd.com/cgi-bin/m/tmauthchecktoken?&token=%s&ou_state=0&okl_token=%s' % ( token, okl_token) check_data = { 'lang': 'chs', 'appid': 300, 'returnurl': 'https://wqlogin2.jd.com/passport/LoginRedirect?state=%s&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action' % check_time_stamp, 'source': 'wq_passport' } check_header = { 'Referer': f'https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=%s&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport' % check_time_stamp, 'Cookie': cookies, 'Connection': 'Keep-Alive', 'Content-Type': 'application/x-www-form-urlencoded; Charset=UTF-8', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', } resp = requests.post(url=check_url, headers=check_header, data=check_data, timeout=30) data = resp.json() if data.get("errcode") == 0: parseJDCookies(resp.headers) await client.delete_messages(chat_id, cookiemsg) await client.send_message(chat_id, '以下为获取到的cookie') await client.send_message(chat_id, jd_cookie) return if data.get("errcode") == 21: await client.delete_messages(chat_id, cookiemsg) await client.send_message(chat_id, '发生了某些错误\n' + data.get("errcode")) return if time.time() > expired_time: await client.delete_messages(chat_id, cookiemsg) await client.send_message(chat_id, '超过3分钟未扫码,二维码已过期') return except Exception as e: await client.send_message(chat_id, 'something wrong,I\'m sorry\n' + str(e)) logger.error('something wrong,I\'m sorry\n' + str(e))
async def inline_id_handler(event: events.InlineQuery.Event): builder = event.builder testinput, shivam = event.pattern_match.group(1).split(";") urllib.parse.quote_plus(testinput) if event.query.user_id == bot.uid: results = [] search = SearchVideos(f"{testinput}", offset=1, mode="dict", max_results=int(shivam)) mi = search.result() moi = mi["search_result"] if search == None: resultm = builder.article( title="No Results.", description="Try Again With correct Spelling", text="**No Matching Found**", buttons=[ [ Button.switch_inline("Search Again", query="yt ", same_peer=True) ], ], ) await event.answer([resultm]) return for mio in moi: mo = mio["link"] thum = mio["title"] fridayz = mio["id"] thums = mio["channel"] td = mio["duration"] tw = mio["views"] kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg" okayz = f"**Title :** `{thum}` \n**Link :** {mo} \n**Channel :** `{thums}` \n**Views :** `{tw}` \n**Duration :** `{td}`" hmmkek = f"Channel : {thums} \nDuration : {td} \nViews : {tw}" results.append(await event.builder.article( title=thum, description=hmmkek, text=okayz, buttons=Button.switch_inline("Search Again", query="yt ", same_peer=True), )) await event.answer(results) if not event.query.user_id == bot.uid: resultm = builder.article( title="me not your bot", description="Mind Your Business", text="Hey U Must Use https://github.com/legendx22/LEGEND-BOT ", buttons=[ [ Button.switch_inline("Search Again", query="yt ", same_peer=True) ], ], ) await event.answer([resultm]) return