__main__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. """
  2. MIT License
  3. Copyright (c) 2024 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 importlib
  22. import re
  23. from contextlib import closing, suppress
  24. from pyrogram import filters, idle
  25. from pyrogram.enums import ChatType, ParseMode
  26. from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
  27. from uvloop import install
  28. from wbb import (
  29. BOT_NAME,
  30. BOT_USERNAME,
  31. LOG_GROUP_ID,
  32. USERBOT_NAME,
  33. aiohttpsession,
  34. app,
  35. log,
  36. )
  37. from wbb.core.keyboard import ikb
  38. from wbb.modules import ALL_MODULES
  39. from wbb.modules.sudoers import bot_sys_stats
  40. from wbb.utils import paginate_modules
  41. from wbb.utils.constants import MARKDOWN
  42. from wbb.utils.dbfunctions import clean_restart_stage, get_rules
  43. from wbb.utils.functions import extract_text_and_keyb
  44. loop = asyncio.get_event_loop()
  45. HELPABLE = {}
  46. async def start_bot():
  47. global HELPABLE
  48. for module in ALL_MODULES:
  49. imported_module = importlib.import_module("wbb.modules." + module)
  50. if (
  51. hasattr(imported_module, "__MODULE__")
  52. and imported_module.__MODULE__
  53. ):
  54. imported_module.__MODULE__ = imported_module.__MODULE__
  55. if (
  56. hasattr(imported_module, "__HELP__")
  57. and imported_module.__HELP__
  58. ):
  59. HELPABLE[
  60. imported_module.__MODULE__.replace(" ", "_").lower()
  61. ] = imported_module
  62. bot_modules = ""
  63. j = 1
  64. for i in ALL_MODULES:
  65. if j == 4:
  66. bot_modules += "|{:<15}|\n".format(i)
  67. j = 0
  68. else:
  69. bot_modules += "|{:<15}".format(i)
  70. j += 1
  71. print("+===============================================================+")
  72. print("| WBB |")
  73. print("+===============+===============+===============+===============+")
  74. print(bot_modules)
  75. print("+===============+===============+===============+===============+")
  76. log.info(f"BOT STARTED AS {BOT_NAME}!")
  77. log.info(f"USERBOT STARTED AS {USERBOT_NAME}!")
  78. restart_data = await clean_restart_stage()
  79. try:
  80. log.info("Sending online status")
  81. if restart_data:
  82. await app.edit_message_text(
  83. restart_data["chat_id"],
  84. restart_data["message_id"],
  85. "**Restarted Successfully**",
  86. )
  87. else:
  88. await app.send_message(LOG_GROUP_ID, "Bot started!")
  89. except Exception:
  90. pass
  91. await idle()
  92. await aiohttpsession.close()
  93. log.info("Stopping clients")
  94. await app.stop()
  95. log.info("Cancelling asyncio tasks")
  96. for task in asyncio.all_tasks():
  97. task.cancel()
  98. log.info("Dead!")
  99. home_keyboard_pm = InlineKeyboardMarkup(
  100. [
  101. [
  102. InlineKeyboardButton(
  103. text="Commands ❓", callback_data="bot_commands"
  104. ),
  105. InlineKeyboardButton(
  106. text="Repo 🛠",
  107. url="https://github.com/thehamkercat/WilliamButcherBot",
  108. ),
  109. ],
  110. [
  111. InlineKeyboardButton(
  112. text="System Stats 🖥",
  113. callback_data="stats_callback",
  114. ),
  115. InlineKeyboardButton(
  116. text="Support 👨", url="http://t.me/WBBSupport"
  117. ),
  118. ],
  119. [
  120. InlineKeyboardButton(
  121. text="Add Me To Your Group 🎉",
  122. url=f"http://t.me/{BOT_USERNAME}?startgroup=new",
  123. )
  124. ],
  125. ]
  126. )
  127. home_text_pm = (
  128. f"Hey there! My name is {BOT_NAME}. I can manage your "
  129. + "group with lots of useful features, feel free to "
  130. + "add me to your group."
  131. )
  132. keyboard = InlineKeyboardMarkup(
  133. [
  134. [
  135. InlineKeyboardButton(
  136. text="Help ❓",
  137. url=f"t.me/{BOT_USERNAME}?start=help",
  138. ),
  139. InlineKeyboardButton(
  140. text="Repo 🛠",
  141. url="https://github.com/thehamkercat/WilliamButcherBot",
  142. ),
  143. ],
  144. [
  145. InlineKeyboardButton(
  146. text="System Stats 💻",
  147. callback_data="stats_callback",
  148. ),
  149. InlineKeyboardButton(text="Support 👨", url="t.me/WBBSupport"),
  150. ],
  151. ]
  152. )
  153. FED_MARKUP = InlineKeyboardMarkup(
  154. [
  155. [
  156. InlineKeyboardButton(
  157. "Fed Owner Commands", callback_data="fed_owner"
  158. ),
  159. InlineKeyboardButton(
  160. "Fed Admin Commands", callback_data="fed_admin"
  161. ),
  162. ],
  163. [
  164. InlineKeyboardButton("User Commands", callback_data="fed_user"),
  165. ],
  166. [
  167. InlineKeyboardButton("Back", callback_data="help_back"),
  168. ],
  169. ]
  170. )
  171. @app.on_message(filters.command("start"))
  172. async def start(_, message):
  173. if message.chat.type != ChatType.PRIVATE:
  174. return await message.reply(
  175. "Pm Me For More Details.", reply_markup=keyboard
  176. )
  177. if len(message.text.split()) > 1:
  178. user = await app.get_users(message.from_user.id)
  179. name = (message.text.split(None, 1)[1]).lower()
  180. match = re.match(r"rules_(.*)", name)
  181. if match:
  182. chat_id = match.group(1)
  183. user_id = message.from_user.id
  184. chat = await app.get_chat(int(chat_id))
  185. text = f"**The rules for `{chat.title}` are:\n\n**"
  186. rules = await get_rules(int(chat_id))
  187. if rules:
  188. text = text + rules
  189. if "{chat}" in text:
  190. text = text.replace("{chat}", chat.title)
  191. if "{name}" in text:
  192. text = text.replace("{name}", user.mention)
  193. keyb = None
  194. if re.findall(r"\[.+\,.+\]", text):
  195. text, keyb = extract_text_and_keyb(ikb, text)
  196. await app.send_message(user_id, text=text, reply_markup=keyb)
  197. else:
  198. return await app.send_message(
  199. user_id,
  200. "The group admins haven't set any rules for this chat yet. "
  201. "This probably doesn't mean it's lawless though...!",
  202. )
  203. if name == "mkdwn_help":
  204. await message.reply(
  205. MARKDOWN,
  206. parse_mode=ParseMode.HTML,
  207. disable_web_page_preview=True,
  208. )
  209. elif "_" in name:
  210. module = name.split("_", 1)[1]
  211. text = (
  212. f"Here is the help for **{HELPABLE[module].__MODULE__}**:\n"
  213. + HELPABLE[module].__HELP__
  214. )
  215. if module == "federation":
  216. return await message.reply(
  217. text=text,
  218. reply_markup=FED_MARKUP,
  219. disable_web_page_preview=True,
  220. )
  221. await message.reply(
  222. text,
  223. reply_markup=InlineKeyboardMarkup(
  224. [[InlineKeyboardButton("back", callback_data="help_back")]]
  225. ),
  226. disable_web_page_preview=True,
  227. )
  228. elif name == "help":
  229. text, keyb = await help_parser(message.from_user.first_name)
  230. await message.reply(
  231. text,
  232. reply_markup=keyb,
  233. )
  234. else:
  235. await message.reply(
  236. home_text_pm,
  237. reply_markup=home_keyboard_pm,
  238. )
  239. return
  240. @app.on_message(filters.command("help"))
  241. async def help_command(_, message):
  242. if message.chat.type != ChatType.PRIVATE:
  243. if len(message.command) >= 2:
  244. name = (message.text.split(None, 1)[1]).replace(" ", "_").lower()
  245. if str(name) in HELPABLE:
  246. key = InlineKeyboardMarkup(
  247. [
  248. [
  249. InlineKeyboardButton(
  250. text="Click here",
  251. url=f"t.me/{BOT_USERNAME}?start=help_{name}",
  252. )
  253. ],
  254. ]
  255. )
  256. await message.reply(
  257. f"Click on the below button to get help about {name}",
  258. reply_markup=key,
  259. )
  260. else:
  261. await message.reply(
  262. "PM Me For More Details.", reply_markup=keyboard
  263. )
  264. else:
  265. await message.reply(
  266. "Pm Me For More Details.", reply_markup=keyboard
  267. )
  268. else:
  269. if len(message.command) >= 2:
  270. name = (message.text.split(None, 1)[1]).replace(" ", "_").lower()
  271. if str(name) in HELPABLE:
  272. text = (
  273. f"Here is the help for **{HELPABLE[name].__MODULE__}**:\n"
  274. + HELPABLE[name].__HELP__
  275. )
  276. await message.reply(text, disable_web_page_preview=True)
  277. else:
  278. text, help_keyboard = await help_parser(
  279. message.from_user.first_name
  280. )
  281. await message.reply(
  282. text,
  283. reply_markup=help_keyboard,
  284. disable_web_page_preview=True,
  285. )
  286. else:
  287. text, help_keyboard = await help_parser(
  288. message.from_user.first_name
  289. )
  290. await message.reply(
  291. text, reply_markup=help_keyboard, disable_web_page_preview=True
  292. )
  293. return
  294. async def help_parser(name, keyboard=None):
  295. if not keyboard:
  296. keyboard = InlineKeyboardMarkup(paginate_modules(0, HELPABLE, "help"))
  297. return (
  298. """Hello {first_name}, My name is {bot_name}.
  299. I'm a group management bot with some useful features.
  300. You can choose an option below, by clicking a button.
  301. Also you can ask anything in Support Group.
  302. """.format(
  303. first_name=name,
  304. bot_name=BOT_NAME,
  305. ),
  306. keyboard,
  307. )
  308. @app.on_callback_query(filters.regex("bot_commands"))
  309. async def commands_callbacc(_, CallbackQuery):
  310. text, keyboard = await help_parser(CallbackQuery.from_user.mention)
  311. await app.send_message(
  312. CallbackQuery.message.chat.id,
  313. text=text,
  314. reply_markup=keyboard,
  315. )
  316. await CallbackQuery.message.delete()
  317. @app.on_callback_query(filters.regex("stats_callback"))
  318. async def stats_callbacc(_, CallbackQuery):
  319. text = await bot_sys_stats()
  320. await app.answer_callback_query(CallbackQuery.id, text, show_alert=True)
  321. @app.on_callback_query(filters.regex(r"help_(.*?)"))
  322. async def help_button(client, query):
  323. home_match = re.match(r"help_home\((.+?)\)", query.data)
  324. mod_match = re.match(r"help_module\((.+?)\)", query.data)
  325. prev_match = re.match(r"help_prev\((.+?)\)", query.data)
  326. next_match = re.match(r"help_next\((.+?)\)", query.data)
  327. back_match = re.match(r"help_back", query.data)
  328. create_match = re.match(r"help_create", query.data)
  329. top_text = f"""
  330. Hello {query.from_user.first_name}, My name is {BOT_NAME}.
  331. I'm a group management bot with some useful features.
  332. You can choose an option below, by clicking a button.
  333. Also you can ask anything in Support Group.
  334. General command are:
  335. - /start: Start the bot
  336. - /help: Give this message
  337. """
  338. if mod_match:
  339. module = (mod_match.group(1)).replace(" ", "_")
  340. text = (
  341. "{} **{}**:\n".format(
  342. "Here is the help for", HELPABLE[module].__MODULE__
  343. )
  344. + HELPABLE[module].__HELP__
  345. )
  346. if module == "federation":
  347. return await query.message.edit(
  348. text=text,
  349. reply_markup=FED_MARKUP,
  350. disable_web_page_preview=True,
  351. )
  352. await query.message.edit(
  353. text=text,
  354. reply_markup=InlineKeyboardMarkup(
  355. [[InlineKeyboardButton("back", callback_data="help_back")]]
  356. ),
  357. disable_web_page_preview=True,
  358. )
  359. elif home_match:
  360. await app.send_message(
  361. query.from_user.id,
  362. text=home_text_pm,
  363. reply_markup=home_keyboard_pm,
  364. )
  365. await query.message.delete()
  366. elif prev_match:
  367. curr_page = int(prev_match.group(1))
  368. await query.message.edit(
  369. text=top_text,
  370. reply_markup=InlineKeyboardMarkup(
  371. paginate_modules(curr_page - 1, HELPABLE, "help")
  372. ),
  373. disable_web_page_preview=True,
  374. )
  375. elif next_match:
  376. next_page = int(next_match.group(1))
  377. await query.message.edit(
  378. text=top_text,
  379. reply_markup=InlineKeyboardMarkup(
  380. paginate_modules(next_page + 1, HELPABLE, "help")
  381. ),
  382. disable_web_page_preview=True,
  383. )
  384. elif back_match:
  385. await query.message.edit(
  386. text=top_text,
  387. reply_markup=InlineKeyboardMarkup(
  388. paginate_modules(0, HELPABLE, "help")
  389. ),
  390. disable_web_page_preview=True,
  391. )
  392. elif create_match:
  393. text, keyboard = await help_parser(query)
  394. await query.message.edit(
  395. text=text,
  396. reply_markup=keyboard,
  397. disable_web_page_preview=True,
  398. )
  399. return await client.answer_callback_query(query.id)
  400. if __name__ == "__main__":
  401. install()
  402. with closing(loop):
  403. with suppress(asyncio.exceptions.CancelledError):
  404. loop.run_until_complete(start_bot())
  405. loop.run_until_complete(asyncio.sleep(3.0)) # task cancel wait