async with" if the event loop is running

那年仲夏 提交于 2021-02-08 06:50:46

问题


I'm writing my first telegram bot with telepot and telethon my main code is:

import sys
import asyncio
import random
import telepot
import telepot.aio
from telepot.aio.loop import MessageLoop
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, ForceReply
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.namedtuple import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent


async def on_chat_message(msg):

    global listenFromKeyboardUsername, listenFromKeyboardPassword, listenFromKeyboardLinkGroup

    content_type, chat_type, chat_id = telepot.glance(msg)
    chat_id = str(chat_id)

    if content_type == 'text':

        name = msg["from"]["first_name"]
        txt = msg['text']

        # stuff..

        elif userExistsInDb and userData['listenFromKeyboardLinkGroup'] and chat_id == doc.id:


            group = telegramGetMessages.checkGroup(txt)
            print(group)


TOKEN = "*******"

bot = telepot.aio.Bot(TOKEN)
answerer = telepot.aio.helper.Answerer(bot)

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot, {'chat': on_chat_message,
                                   'callback_query': on_callback_query}).run_forever())
print('Listening ...')

loop.run_forever()

from the code above I call the checkGroup function:

def checkGroup(hash):
    initClient()
    global result

    hash = hash.replace('https://t.me/joinchat/', '')
    with TelegramClient(name, api_id, api_hash) as client:
        result = client(functions.messages.CheckChatInviteRequest(hash=hash))

    if isinstance(result, ChatInvite):
        print('You are not inside the group')
        with TelegramClient(name, api_id, api_hash) as client:
            client(functions.messages.ImportChatInviteRequest(hash=hash))
            result = client(functions.messages.CheckChatInviteRequest(hash=hash))


    return result

where I'm getting this error:

 RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")

then I edit the checkGroup function with async def checkGroup(hash): ..

but now I'm geting this error and I don't know what to do:
Task exception was never retrieved
future: <Task finished coro=<Router.route() done, defined at /home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py:213> exception=NotFound('No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups',)>
Traceback (most recent call last):
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/grpc/_channel.py", line 549, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/grpc/_channel.py", line 466, in _end_unary_response_blocking
    raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
    status = StatusCode.NOT_FOUND
    details = "No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups"
    debug_error_string = "{"created":"@1552727386.760400590","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1039,"grpc_message":"No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups","grpc_status":5}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py", line 244, in route
    return await _invoke(fn, msg, *args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py", line 16, in _invoke
    return await fn(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/chatAsync.py", line 119, in on_chat_message
    database.updateUserData(chat_id, 'groups', 'nameGroup', txt)
  File "/home/ale/PycharmProjects/newTelegramBot/database.py", line 38, in updateUserData
    field: key,
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/document.py", line 371, in update
    write_results = batch.commit()
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/batch.py", line 148, in commit
    metadata=self._client._rpc_metadata,
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/gapic/firestore_client.py", line 946, in commit
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/retry.py", line 270, in retry_wrapped_func
    on_error=on_error,
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/retry.py", line 179, in retry_target
    return target()
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
    return func(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.NotFound: 404 No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups
/usr/lib/python3.6/asyncio/base_events.py:1441: RuntimeWarning: coroutine 'checkGroup' was never awaited
  handle = None  # Needed to break cycles when an exception occurs.

I'm reading around, and maybe for this problem it's better to use the delegatoBot, but I'm not really sure because I can't find great examples! It wold be wonderfull recive a reply, If you need anything just ask! Thankyou

来源:https://stackoverflow.com/questions/55196673/async-with-if-the-event-loop-is-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!