inlinefuncs.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. """
  2. MIT License
  3. Copyright (c) 2021 TheHamkerCat
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. import asyncio
  21. import os
  22. import sys
  23. from html import escape
  24. from re import sub as re_sub
  25. from sys import version as pyver
  26. from time import ctime, time
  27. from fuzzysearch import find_near_matches
  28. from motor import version as mongover
  29. from pykeyboard import InlineKeyboard
  30. from pyrogram import __version__ as pyrover
  31. from pyrogram import filters
  32. from pyrogram.raw.functions import Ping
  33. from pyrogram.types import (CallbackQuery, InlineKeyboardButton,
  34. InlineQueryResultArticle, InlineQueryResultPhoto,
  35. InputTextMessageContent)
  36. from search_engine_parser import GoogleSearch
  37. from wbb import (BOT_USERNAME, MESSAGE_DUMP_CHAT, SUDOERS, USERBOT_ID,
  38. USERBOT_NAME, USERBOT_USERNAME, app, app2, arq)
  39. from wbb.core.keyboard import ikb
  40. from wbb.core.tasks import _get_tasks_text, all_tasks, rm_task
  41. from wbb.core.types import InlineQueryResultCachedDocument
  42. from wbb.modules.info import get_chat_info, get_user_info
  43. from wbb.modules.music import download_youtube_audio
  44. from wbb.utils.functions import test_speedtest
  45. from wbb.utils.pastebin import paste
  46. keywords_list = [
  47. "image",
  48. "wall",
  49. "tmdb",
  50. "lyrics",
  51. "exec",
  52. "speedtest",
  53. "search",
  54. "ping",
  55. "tr",
  56. "ud",
  57. "yt",
  58. "info",
  59. "google",
  60. "torrent",
  61. "wiki",
  62. "music",
  63. "ytmusic",
  64. ]
  65. async def inline_help_func(__HELP__):
  66. buttons = InlineKeyboard(row_width=4)
  67. buttons.add(
  68. *[
  69. (InlineKeyboardButton(text=i, switch_inline_query_current_chat=i))
  70. for i in keywords_list
  71. ]
  72. )
  73. answerss = [
  74. InlineQueryResultArticle(
  75. title="Inline Commands",
  76. description="Help Related To Inline Usage.",
  77. input_message_content=InputTextMessageContent(
  78. "Click A Button To Get Started."
  79. ),
  80. thumb_url="https://hamker.me/cy00x5x.png",
  81. reply_markup=buttons,
  82. ),
  83. InlineQueryResultArticle(
  84. title="Github Repo",
  85. description="Get Github Respository Of Bot.",
  86. input_message_content=InputTextMessageContent(
  87. "https://github.com/thehamkercat/WilliamButcherBot"
  88. ),
  89. thumb_url="https://hamker.me/gjc9fo3.png",
  90. ),
  91. ]
  92. answerss = await alive_function(answerss)
  93. return answerss
  94. async def alive_function(answers):
  95. buttons = InlineKeyboard(row_width=2)
  96. bot_state = "Dead" if not await app.get_me() else "Alive"
  97. ubot_state = "Dead" if not await app2.get_me() else "Alive"
  98. buttons.add(
  99. InlineKeyboardButton("Stats", callback_data="stats_callback"),
  100. InlineKeyboardButton(
  101. "Go Inline!", switch_inline_query_current_chat=""
  102. ),
  103. )
  104. msg = f"""
  105. **[William✨](https://github.com/thehamkercat/WilliamButcherBot):**
  106. **MainBot:** `{bot_state}`
  107. **UserBot:** `{ubot_state}`
  108. **Python:** `{pyver.split()[0]}`
  109. **Pyrogram:** `{pyrover}`
  110. **MongoDB:** `{mongover}`
  111. **Platform:** `{sys.platform}`
  112. **Profiles:** [BOT](t.me/{BOT_USERNAME}) | [UBOT](t.me/{USERBOT_USERNAME})
  113. """
  114. answers.append(
  115. InlineQueryResultArticle(
  116. title="Alive",
  117. description="Check Bot's Stats",
  118. thumb_url="https://static2.aniimg.com/upload/20170515/414/c/d/7/cd7EEF.jpg",
  119. input_message_content=InputTextMessageContent(
  120. msg, disable_web_page_preview=True
  121. ),
  122. reply_markup=buttons,
  123. )
  124. )
  125. return answers
  126. async def translate_func(answers, lang, tex):
  127. result = await arq.translate(tex, lang)
  128. if not result.ok:
  129. answers.append(
  130. InlineQueryResultArticle(
  131. title="Error",
  132. description=result.result,
  133. input_message_content=InputTextMessageContent(result.result),
  134. )
  135. )
  136. return answers
  137. result = result.result
  138. msg = f"""
  139. __**Translated from {result.src} to {result.dest}**__
  140. **INPUT:**
  141. {tex}
  142. **OUTPUT:**
  143. {result.translatedText}"""
  144. answers.extend(
  145. [
  146. InlineQueryResultArticle(
  147. title=f"Translated from {result.src} to {result.dest}.",
  148. description=result.translatedText,
  149. input_message_content=InputTextMessageContent(msg),
  150. ),
  151. InlineQueryResultArticle(
  152. title=result.translatedText,
  153. input_message_content=InputTextMessageContent(
  154. result.translatedText
  155. ),
  156. ),
  157. ]
  158. )
  159. return answers
  160. async def urban_func(answers, text):
  161. results = await arq.urbandict(text)
  162. if not results.ok:
  163. answers.append(
  164. InlineQueryResultArticle(
  165. title="Error",
  166. description=results.result,
  167. input_message_content=InputTextMessageContent(results.result),
  168. )
  169. )
  170. return answers
  171. results = results.result[0:48]
  172. for i in results:
  173. clean = lambda x: re_sub(r"[\[\]]", "", x)
  174. msg = f"""
  175. **Query:** {text}
  176. **Definition:** __{clean(i.definition)}__
  177. **Example:** __{clean(i.example)}__"""
  178. answers.append(
  179. InlineQueryResultArticle(
  180. title=i.word,
  181. description=clean(i.definition),
  182. input_message_content=InputTextMessageContent(msg),
  183. )
  184. )
  185. return answers
  186. async def google_search_func(answers, text):
  187. gresults = await GoogleSearch().async_search(text)
  188. limit = 0
  189. for i in gresults:
  190. if limit > 48:
  191. break
  192. limit += 1
  193. try:
  194. msg = f"""
  195. [{i['titles']}]({i['links']})
  196. {i['descriptions']}"""
  197. answers.append(
  198. InlineQueryResultArticle(
  199. title=i["titles"],
  200. description=i["descriptions"],
  201. input_message_content=InputTextMessageContent(
  202. msg, disable_web_page_preview=True
  203. ),
  204. )
  205. )
  206. except KeyError:
  207. pass
  208. return answers
  209. async def wall_func(answers, text):
  210. results = await arq.wall(text)
  211. if not results.ok:
  212. answers.append(
  213. InlineQueryResultArticle(
  214. title="Error",
  215. description=results.result,
  216. input_message_content=InputTextMessageContent(results.result),
  217. )
  218. )
  219. return answers
  220. results = results.result[0:48]
  221. for i in results:
  222. answers.append(
  223. InlineQueryResultPhoto(
  224. photo_url=i.url_image,
  225. thumb_url=i.url_thumb,
  226. caption=f"[Source]({i.url_image})",
  227. )
  228. )
  229. return answers
  230. async def torrent_func(answers, text):
  231. results = await arq.torrent(text)
  232. if not results.ok:
  233. answers.append(
  234. InlineQueryResultArticle(
  235. title="Error",
  236. description=results.result,
  237. input_message_content=InputTextMessageContent(results.result),
  238. )
  239. )
  240. return answers
  241. results = results.result[0:48]
  242. for i in results:
  243. title = i.name
  244. size = i.size
  245. seeds = i.seeds
  246. leechs = i.leechs
  247. upload_date = i.uploaded
  248. magnet = i.magnet
  249. caption = f"""
  250. **Title:** __{title}__
  251. **Size:** __{size}__
  252. **Seeds:** __{seeds}__
  253. **Leechs:** __{leechs}__
  254. **Uploaded:** __{upload_date}__
  255. **Magnet:** `{magnet}`"""
  256. description = f"{size} | {upload_date} | Seeds: {seeds}"
  257. answers.append(
  258. InlineQueryResultArticle(
  259. title=title,
  260. description=description,
  261. input_message_content=InputTextMessageContent(
  262. caption, disable_web_page_preview=True
  263. ),
  264. )
  265. )
  266. pass
  267. return answers
  268. async def youtube_func(answers, text):
  269. results = await arq.youtube(text)
  270. if not results.ok:
  271. answers.append(
  272. InlineQueryResultArticle(
  273. title="Error",
  274. description=results.result,
  275. input_message_content=InputTextMessageContent(results.result),
  276. )
  277. )
  278. return answers
  279. results = results.result[0:48]
  280. for i in results:
  281. buttons = InlineKeyboard(row_width=1)
  282. video_url = f"https://youtube.com{i.url_suffix}"
  283. buttons.add(InlineKeyboardButton("Watch", url=video_url))
  284. caption = f"""
  285. **Title:** {i.title}
  286. **Views:** {i.views}
  287. **Channel:** {i.channel}
  288. **Duration:** {i.duration}
  289. **Uploaded:** {i.publish_time}
  290. **Description:** {i.long_desc}"""
  291. description = (
  292. f"{i.views} | {i.channel} | {i.duration} | {i.publish_time}"
  293. )
  294. answers.append(
  295. InlineQueryResultArticle(
  296. title=i.title,
  297. thumb_url=i.thumbnails[0],
  298. description=description,
  299. input_message_content=InputTextMessageContent(
  300. caption, disable_web_page_preview=True
  301. ),
  302. reply_markup=buttons,
  303. )
  304. )
  305. return answers
  306. async def lyrics_func(answers, text):
  307. song = await arq.lyrics(text)
  308. if not song.ok:
  309. answers.append(
  310. InlineQueryResultArticle(
  311. title="Error",
  312. description=song.result,
  313. input_message_content=InputTextMessageContent(song.result),
  314. )
  315. )
  316. return answers
  317. lyrics = song.result
  318. song = lyrics.splitlines()
  319. song_name = song[0]
  320. artist = song[1]
  321. if len(lyrics) > 4095:
  322. lyrics = await paste(lyrics)
  323. lyrics = f"**LYRICS_TOO_LONG:** [URL]({lyrics})"
  324. msg = f"__{lyrics}__"
  325. answers.append(
  326. InlineQueryResultArticle(
  327. title=song_name,
  328. description=artist,
  329. input_message_content=InputTextMessageContent(msg),
  330. )
  331. )
  332. return answers
  333. async def tg_search_func(answers, text, user_id):
  334. if user_id not in SUDOERS:
  335. msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
  336. answers.append(
  337. InlineQueryResultArticle(
  338. title="ERROR",
  339. description="THIS FEATURE IS ONLY FOR SUDO USERS",
  340. input_message_content=InputTextMessageContent(msg),
  341. )
  342. )
  343. return answers
  344. if str(text)[-1] != ":":
  345. msg = "**ERROR**\n__Put A ':' After The Text To Search__"
  346. answers.append(
  347. InlineQueryResultArticle(
  348. title="ERROR",
  349. description="Put A ':' After The Text To Search",
  350. input_message_content=InputTextMessageContent(msg),
  351. )
  352. )
  353. return answers
  354. text = text[0:-1]
  355. async for message in app2.search_global(text, limit=49):
  356. buttons = InlineKeyboard(row_width=2)
  357. buttons.add(
  358. InlineKeyboardButton(
  359. text="Origin",
  360. url=message.link if message.link else "https://t.me/telegram",
  361. ),
  362. InlineKeyboardButton(
  363. text="Search again",
  364. switch_inline_query_current_chat="search",
  365. ),
  366. )
  367. name = (
  368. message.from_user.first_name
  369. if message.from_user.first_name
  370. else "NO NAME"
  371. )
  372. caption = f"""
  373. **Query:** {text}
  374. **Name:** {str(name)} [`{message.from_user.id}`]
  375. **Chat:** {str(message.chat.title)} [`{message.chat.id}`]
  376. **Date:** {ctime(message.date)}
  377. **Text:** >>
  378. {message.text.markdown if message.text else message.caption if message.caption else '[NO_TEXT]'}
  379. """
  380. result = InlineQueryResultArticle(
  381. title=name,
  382. description=message.text if message.text else "[NO_TEXT]",
  383. reply_markup=buttons,
  384. input_message_content=InputTextMessageContent(
  385. caption, disable_web_page_preview=True
  386. ),
  387. )
  388. answers.append(result)
  389. return answers
  390. async def music_inline_func(answers, query):
  391. chat_id = -1001445180719
  392. group_invite = "https://t.me/joinchat/vSDE2DuGK4Y4Nzll"
  393. try:
  394. messages = [
  395. m
  396. async for m in app2.search_messages(
  397. chat_id, query, filter="audio", limit=100
  398. )
  399. ]
  400. except Exception as e:
  401. print(e)
  402. msg = f"You Need To Join Here With Your Bot And Userbot To Get Cached Music.\n{group_invite}"
  403. answers.append(
  404. InlineQueryResultArticle(
  405. title="ERROR",
  406. description="Click Here To Know More.",
  407. input_message_content=InputTextMessageContent(
  408. msg, disable_web_page_preview=True
  409. ),
  410. )
  411. )
  412. return answers
  413. messages_ids_and_duration = []
  414. for f_ in messages:
  415. messages_ids_and_duration.append(
  416. {
  417. "message_id": f_.message_id,
  418. "duration": f_.audio.duration if f_.audio.duration else 0,
  419. }
  420. )
  421. messages = list(
  422. {v["duration"]: v for v in messages_ids_and_duration}.values()
  423. )
  424. messages_ids = [ff_["message_id"] for ff_ in messages]
  425. messages = await app.get_messages(chat_id, messages_ids[0:48])
  426. return [
  427. InlineQueryResultCachedDocument(
  428. file_id=message_.audio.file_id,
  429. title=message_.audio.title,
  430. )
  431. for message_ in messages
  432. ]
  433. async def wiki_func(answers, text):
  434. data = await arq.wiki(text)
  435. if not data.ok:
  436. answers.append(
  437. InlineQueryResultArticle(
  438. title="Error",
  439. description=data.result,
  440. input_message_content=InputTextMessageContent(data.result),
  441. )
  442. )
  443. return answers
  444. data = data.result
  445. msg = f"""
  446. **QUERY:**
  447. {data.title}
  448. **ANSWER:**
  449. __{data.answer}__"""
  450. answers.append(
  451. InlineQueryResultArticle(
  452. title=data.title,
  453. description=data.answer,
  454. input_message_content=InputTextMessageContent(msg),
  455. )
  456. )
  457. return answers
  458. async def speedtest_init(query):
  459. answers = []
  460. user_id = query.from_user.id
  461. if user_id not in SUDOERS:
  462. msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
  463. answers.append(
  464. InlineQueryResultArticle(
  465. title="ERROR",
  466. description="THIS FEATURE IS ONLY FOR SUDO USERS",
  467. input_message_content=InputTextMessageContent(msg),
  468. )
  469. )
  470. return answers
  471. msg = "**Click The Button Below To Perform A Speedtest**"
  472. button = InlineKeyboard(row_width=1)
  473. button.add(
  474. InlineKeyboardButton(text="Test", callback_data="test_speedtest")
  475. )
  476. answers.append(
  477. InlineQueryResultArticle(
  478. title="Click Here",
  479. input_message_content=InputTextMessageContent(msg),
  480. reply_markup=button,
  481. )
  482. )
  483. return answers
  484. # CallbackQuery for the function above
  485. @app.on_callback_query(filters.regex("test_speedtest"))
  486. async def test_speedtest_cq(_, cq):
  487. if cq.from_user.id not in SUDOERS:
  488. return await cq.answer("This Isn't For You!")
  489. inline_message_id = cq.inline_message_id
  490. await app.edit_inline_text(inline_message_id, "**Testing**")
  491. loop = asyncio.get_running_loop()
  492. download, upload, info = await loop.run_in_executor(None, test_speedtest)
  493. msg = f"""
  494. **Download:** `{download}`
  495. **Upload:** `{upload}`
  496. **Latency:** `{info['latency']} ms`
  497. **Country:** `{info['country']} [{info['cc']}]`
  498. **Latitude:** `{info['lat']}`
  499. **Longitude:** `{info['lon']}`
  500. """
  501. await app.edit_inline_text(inline_message_id, msg)
  502. async def pmpermit_func(answers, user_id, victim):
  503. if user_id != USERBOT_ID:
  504. return
  505. caption = f"Hi, I'm {USERBOT_NAME}, What are you here for?, You'll be blocked if you send more than 5 messages."
  506. buttons = InlineKeyboard(row_width=2)
  507. buttons.add(
  508. InlineKeyboardButton(
  509. text="To Scam You", callback_data="pmpermit to_scam_you a"
  510. ),
  511. InlineKeyboardButton(
  512. text="For promotion",
  513. callback_data="pmpermit to_scam_you a",
  514. ),
  515. InlineKeyboardButton(
  516. text="Approve me", callback_data="pmpermit approve_me a"
  517. ),
  518. InlineKeyboardButton(
  519. text="Approve", callback_data=f"pmpermit approve {victim}"
  520. ),
  521. InlineKeyboardButton(
  522. text="Block & Delete",
  523. callback_data=f"pmpermit block {victim}",
  524. ),
  525. )
  526. answers.append(
  527. InlineQueryResultArticle(
  528. title="do_not_click_here",
  529. reply_markup=buttons,
  530. input_message_content=InputTextMessageContent(caption),
  531. )
  532. )
  533. return answers
  534. async def ping_func(answers):
  535. ping = Ping(ping_id=app.rnd_id())
  536. t1 = time()
  537. await app.send(ping)
  538. t2 = time()
  539. ping = f"{str(round((t2 - t1) * 1000, 2))} ms"
  540. answers.append(
  541. InlineQueryResultArticle(
  542. title=ping,
  543. input_message_content=InputTextMessageContent(f"__**{ping}**__"),
  544. )
  545. )
  546. return answers
  547. async def yt_music_func(answers, url):
  548. arq_resp = await arq.youtube(url)
  549. loop = asyncio.get_running_loop()
  550. music = await loop.run_in_executor(None, download_youtube_audio, arq_resp)
  551. if not music:
  552. msg = "**ERROR**\n__MUSIC TOO LONG__"
  553. answers.append(
  554. InlineQueryResultArticle(
  555. title="ERROR",
  556. description="MUSIC TOO LONG",
  557. input_message_content=InputTextMessageContent(msg),
  558. )
  559. )
  560. return answers
  561. (
  562. title,
  563. performer,
  564. duration,
  565. audio,
  566. thumbnail,
  567. ) = music
  568. m = await app.send_audio(
  569. MESSAGE_DUMP_CHAT,
  570. audio,
  571. title=title,
  572. duration=duration,
  573. performer=performer,
  574. thumb=thumbnail,
  575. )
  576. os.remove(audio)
  577. os.remove(thumbnail)
  578. answers.append(
  579. InlineQueryResultCachedDocument(title=title, file_id=m.audio.file_id)
  580. )
  581. return answers
  582. async def info_inline_func(answers, peer):
  583. not_found = InlineQueryResultArticle(
  584. title="PEER NOT FOUND",
  585. input_message_content=InputTextMessageContent("PEER NOT FOUND"),
  586. )
  587. try:
  588. user = await app.get_users(peer)
  589. caption, _ = await get_user_info(user, True)
  590. except IndexError:
  591. try:
  592. chat = await app.get_chat(peer)
  593. caption, _ = await get_chat_info(chat, True)
  594. except Exception:
  595. return [not_found]
  596. except Exception:
  597. return [not_found]
  598. answers.append(
  599. InlineQueryResultArticle(
  600. title="Found Peer.",
  601. input_message_content=InputTextMessageContent(
  602. caption, disable_web_page_preview=True
  603. ),
  604. )
  605. )
  606. return answers
  607. async def tmdb_func(answers, query):
  608. response = await arq.tmdb(query)
  609. if not response.ok:
  610. answers.append(
  611. InlineQueryResultArticle(
  612. title="Error",
  613. description=response.result,
  614. input_message_content=InputTextMessageContent(response.result),
  615. )
  616. )
  617. return answers
  618. results = response.result[:49]
  619. for result in results:
  620. if not result.poster and not result.backdrop:
  621. continue
  622. if not result.genre:
  623. genre = None
  624. else:
  625. genre = " | ".join(result.genre)
  626. description = result.overview[0:900] if result.overview else "None"
  627. caption = f"""
  628. **{result.title}**
  629. **Type:** {result.type}
  630. **Rating:** {result.rating}
  631. **Genre:** {genre}
  632. **Release Date:** {result.releaseDate}
  633. **Description:** __{description}__
  634. """
  635. buttons = InlineKeyboard(row_width=1)
  636. buttons.add(
  637. InlineKeyboardButton(
  638. "Search Again",
  639. switch_inline_query_current_chat="tmdb",
  640. )
  641. )
  642. answers.append(
  643. InlineQueryResultPhoto(
  644. photo_url=result.backdrop
  645. if result.backdrop
  646. else result.poster,
  647. caption=caption,
  648. title=result.title,
  649. description=f"{genre} • {result.releaseDate} • {result.rating} • {description}",
  650. reply_markup=buttons,
  651. )
  652. )
  653. return answers
  654. async def image_func(answers, query):
  655. results = await arq.image(query)
  656. if not results.ok:
  657. answers.append(
  658. InlineQueryResultArticle(
  659. title="Error",
  660. description=results.result,
  661. input_message_content=InputTextMessageContent(results.result),
  662. )
  663. )
  664. return answers
  665. results = results.result[:49]
  666. buttons = InlineKeyboard(row_width=2)
  667. buttons.add(
  668. InlineKeyboardButton(
  669. text="Search again",
  670. switch_inline_query_current_chat="image",
  671. ),
  672. )
  673. for i in results:
  674. answers.append(
  675. InlineQueryResultPhoto(
  676. title=i.title,
  677. photo_url=i.url,
  678. thumb_url=i.url,
  679. reply_markup=buttons,
  680. )
  681. )
  682. return answers
  683. async def execute_code(query):
  684. text = query.query.strip()
  685. offset = int((query.offset or 0))
  686. answers = []
  687. languages = (await arq.execute()).result
  688. if len(text.split()) == 1:
  689. answers = [
  690. InlineQueryResultArticle(
  691. title=lang,
  692. input_message_content=InputTextMessageContent(lang),
  693. )
  694. for lang in languages
  695. ][offset : offset + 25]
  696. await query.answer(
  697. next_offset=str(offset + 25),
  698. results=answers,
  699. cache_time=1,
  700. )
  701. elif len(text.split()) == 2:
  702. text = text.split()[1].strip()
  703. languages = list(
  704. filter(
  705. lambda x: find_near_matches(text, x, max_l_dist=1),
  706. languages,
  707. )
  708. )
  709. answers.extend(
  710. [
  711. InlineQueryResultArticle(
  712. title=lang,
  713. input_message_content=InputTextMessageContent(lang),
  714. )
  715. for lang in languages
  716. ][:49]
  717. )
  718. else:
  719. lang = text.split()[1]
  720. code = text.split(None, 2)[2]
  721. response = await arq.execute(lang, code)
  722. if not response.ok:
  723. answers.append(
  724. InlineQueryResultArticle(
  725. title="Error",
  726. input_message_content=InputTextMessageContent(
  727. response.result
  728. ),
  729. )
  730. )
  731. else:
  732. res = response.result
  733. stdout, stderr = escape(res.stdout), escape(res.stderr)
  734. output = stdout or stderr
  735. out = "STDOUT" if stdout else ("STDERR" if stderr else "No output")
  736. msg = f"""
  737. **{lang.capitalize()}:**
  738. ```{code}```
  739. **{out}:**
  740. ```{output}```
  741. """
  742. answers.append(
  743. InlineQueryResultArticle(
  744. title="Executed",
  745. description=output[:20],
  746. input_message_content=InputTextMessageContent(msg),
  747. )
  748. )
  749. await query.answer(results=answers, cache_time=1)
  750. async def task_inline_func(user_id):
  751. if user_id not in SUDOERS:
  752. return
  753. tasks = all_tasks()
  754. text = await _get_tasks_text()
  755. keyb = None
  756. if tasks:
  757. keyb = ikb(
  758. {i: f"cancel_task_{i}" for i in list(tasks.keys())},
  759. row_width=4,
  760. )
  761. return [
  762. InlineQueryResultArticle(
  763. title="Tasks",
  764. reply_markup=keyb,
  765. input_message_content=InputTextMessageContent(
  766. text,
  767. ),
  768. )
  769. ]
  770. @app.on_callback_query(filters.regex("^cancel_task_"))
  771. async def cancel_task_button(_, query: CallbackQuery):
  772. user_id = query.from_user.id
  773. if user_id not in SUDOERS:
  774. return await query.answer("This is not for you.")
  775. task_id = int(query.data.split("_")[-1])
  776. await rm_task(task_id)
  777. tasks = all_tasks()
  778. text = await _get_tasks_text()
  779. keyb = None
  780. if tasks:
  781. keyb = ikb({i: f"cancel_task_{i}" for i in list(tasks.keys())})
  782. await app.edit_inline_text(
  783. query.inline_message_id,
  784. text,
  785. )
  786. if keyb:
  787. await app.edit_inline_reply_markup(
  788. query.inline_message_id,
  789. keyb,
  790. )