Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to implement Telethon into flask-restful, but I am coming across an error
TypeError: Object of type coroutine is not JSON serializable
I started out with all of the calls to Telethon in one asynced post method, but I have since moved much of the Telethon code outside.
I also saw a similar post on SO
here
but it was not fully answered.
Here is the code:
api_endpoints = Blueprint('api_endpoints', __name__)
api = Api(api_endpoints)
api_id = os.environ.get('API_ID')
api_hash = os.environ.get('API_HASH')
words = mnemonic.Mnemonic('english').generate(strength=128)
bot_name = words.replace(' ', '')
print(bot_name[:16])
client = TelegramClient('anon', api_id, api_hash)
@client.on(events.NewMessage(chats='BotFather',
pattern='Alright, a new bot.'))
async def receive_first_message(event):
return await event.reply(bot_name)
@client.on(events.NewMessage(chats='BotFather',
pattern='Good. Now let\'s choose a username for your bot.'))
async def receive_second_message(event):
name = bot_name + '_bot'
return await event.reply(name)
@client.on(events.NewMessage(chats='BotFather',
pattern='Done! Congratulations on your new bot.'))
async def receive_third_message(event):
if 'Use this token to access the HTTP API' in event.raw_text:
token = event.raw_text.split('Use this token to access the HTTP API: ')[1]
await client.disconnect()
return {'token': token}
else:
print(event.raw_text)
async def telegram_creation_mgmt():
await client.start()
await client.send_message('BotFather', '/newbot')
# execute the handlers
task1 = client.loop.create_task(receive_first_message())
task2 = client.loop.create_task(receive_second_message())
task3 = client.loop.create_task(receive_third_message())
await client.run_until_disconnected()
return {"message": "success"}
class TelegramCreateBot(Resource):
def post(self):
return telegram_creation_mgmt()
api.add_resource(TelegramCreateBot, '/createtelegrambot')
Here is the full error:
127.0.0.1 - - [02/Apr/2023 18:51:09] "POST /createtelegrambot HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask_restful/__init__.py", line 471, in wrapper
return self.make_response(data, code, headers=headers)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask_restful/__init__.py", line 500, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)
File "/Users/12345/opt/anaconda3/lib/python3.9/site-packages/flask_restful/representations/json.py", line 21, in output_json
dumped = dumps(data, **settings) + "\n"
File "/Users/12345/opt/anaconda3/lib/python3.9/json/__init__.py", line 234, in dumps
return cls(
File "/Users/12345/opt/anaconda3/lib/python3.9/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/Users/12345/opt/anaconda3/lib/python3.9/json/encoder.py", line 438, in _iterencode
o = _default(o)
File "/Users/12345/opt/anaconda3/lib/python3.9/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type coroutine is not JSON serializable
This is an async function, calling it will make it a coroutine, you must do await
(under async context) or asyncio.run(func()) first to retrieve its return.
About this part:
task1 = client.loop.create_task(receive_first_message())
await client.run_until_disconnected()
This is useless. when you do @client.on, the async defs under the decorator will be added to internal list of event builders and will be executed in concurrent way by themselves, you only need to run the event loop and lock it running (with client.run_until_disconnected() for example), so only the last line is enough.
also, more than useless, it is wrong. you will be calling all the callbacks without the events being triggered (sent by Telegram).. and you're not passing them the argument (event), the telethon will deal with event, you just @client.on them
you might be also interested in checking the client.conversation for staged concurrent way of sending a message to a chat and retrieving its response or reply, to avoid collision and misorder. that's for another question.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.