Created
November 14, 2020 23:00
-
-
Save MasterGroosha/b8ed2bbe93e10b9836125788947f6b56 to your computer and use it in GitHub Desktop.
The simpliest CLI for aiogram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import shlex | |
from aiogram import Bot | |
from json import loads, dumps | |
# Suppress DeprecationWarning from close() method | |
import logging | |
logging.captureWarnings(True) | |
token = "1234567:YOUR_TOKEN" | |
async def exec_method(method: str, *args, **kwargs): | |
if not hasattr(Bot, method): | |
return f"No such method: {method}" | |
bot = Bot(token=token) | |
function_to_call = getattr(bot, method) | |
result = await function_to_call(*args, **kwargs) | |
await bot.close() | |
# For some reason, pprint didn't format {result} properly | |
# Maybe you have more luck than me? | |
return dumps(loads(str(result)), indent=2, ensure_ascii=False) | |
async def main(): | |
while True: | |
request = input("Enter command with arguments: ") | |
args = [] | |
kwargs = {} | |
parts = shlex.split(request) | |
if len(parts) == 0: | |
print("Cannot handle empty commands!") | |
continue | |
elif len(parts) == 1: | |
print(await exec_method(parts[0])) | |
continue | |
else: | |
for item in parts[1:]: | |
if "=" in item: | |
item_split = item.split("=", maxsplit=1) | |
kwargs[item_split[0]] = item_split[1] | |
else: | |
args.append(item) | |
result = await exec_method(parts[0], *args, **kwargs) | |
print(result) | |
continue | |
if __name__ == '__main__': | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment