Telethon client.connect()在本地工作,但不与docker容器一起工作

2024-10-02 08:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试部署一个python telethon web应用程序(使用quart),当我在本地测试时,telethon可以毫无问题地连接到电报帐户,但当我在docker容器中测试时,连接失败

以下是日志:

enter image description here

(然后卡在那里)

dockerfile:

# Use the official lightweight Python image.
# https://hub.docker.com/_/python
FROM python:3.9-slim

# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

COPY sessionname.session ./sessionname.session

# Install production dependencies.
RUN pip install --no-cache-dir -r requirements.txt

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --worker-class uvicorn.workers.UvicornWorker --bind :$PORT --workers 1 --preload --threads 8 --timeout 1500 main:app

还有我的main.py文件

import base64
import os
import json
import hypercorn.asyncio
import logging

from quart import jsonify, Quart, render_template_string, request
from telethon import TelegramClient, utils
from telethon.tl.types import InputChannel, InputPeerChannel, InputPhoneContact, InputPeerUser
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.errors import SessionPasswordNeededError
from telethon.tl.functions.messages import ExportChatInviteRequest, SendMessageRequest
from telethon.tl.functions.channels import CreateChannelRequest, CheckUsernameRequest, UpdateUsernameRequest, SetDiscussionGroupRequest, ToggleSignaturesRequest, InviteToChannelRequest
from requests.models import Response

logging.basicConfig(level=logging.DEBUG)

api_id = xxxx
api_hash = 'xxxxx'

#phone numberI
phone_number = '+xxxx'

print("create and connect to the telegram client")

client = TelegramClient('sessionname', api_id, api_hash)

app = Quart(__name__)

# Connect the client before we start serving with Quart
@app.before_serving
async def startup():
    print("run before_serving!! (waiting for connection)")
    try:
        await client.start()
    except:
        print ("Could not connect to telegram")

    print("connect is OK!!")

# After we're done serving (near shutdown), clean up the client
@app.after_serving
async def cleanup():
    print("after serving ok!")
    await client.disconnect()

@app.route('/check', methods=['POST'])
async def sayHello():
    return "hola"

@app.route('/channel/create', methods=['POST'])
async def createChannel():
    
    strBody = await request.get_data()

    parsedBody = json.loads(strBody)

    # Create the channel
    createdPrivateChannel = await client(CreateChannelRequest(parsedBody["title"], parsedBody["about"], megagroup=False))

    # Create the supergroup for the comments
    discussionSuperGroup = await client(CreateChannelRequest(parsedBody["title"], parsedBody["about"], megagroup=True))

    await client(SetDiscussionGroupRequest(createdPrivateChannel.__dict__["chats"][0].__dict__["id"], discussionSuperGroup.__dict__["chats"][0].__dict__["id"]))

    # Send welcome message to the channel
    welcomeMessageResult = await client(SendMessageRequest(
        createdPrivateChannel.__dict__["chats"][0].__dict__["id"],
        'Bienvenidx',
        True
    ))

    # Enable signature in messages
    toggleSignatureResult = await client(ToggleSignaturesRequest(
        createdPrivateChannel.__dict__["chats"][0].__dict__["id"],
        True
    ))

    # # Invite the bots to the channel
    # inviteToChannelResult = await client(InviteToChannelRequest(
    #     createdPrivateChannel.__dict__["chats"][0].__dict__["id"],
    #     ['userIdOfTheBot']
    # ))

    # Create an invitation link
    channelInviteLink = await client(ExportChatInviteRequest(
        createdPrivateChannel.__dict__["chats"][0].__dict__["id"]
    ))

    response = jsonify({
        "channel_id": createdPrivateChannel.__dict__["chats"][0].__dict__["id"], 
        "title": parsedBody["title"],
        "about": parsedBody["about"],
        "chat_invite_link": channelInviteLink.__dict__["link"]
    })

    return response


async def main():
    quart_cfg = hypercorn.Config()
    quart_cfg.bind = ["0.0.0.0:8888"]
    await hypercorn.asyncio.serve(app, quart_cfg)

if __name__ == '__main__':
    client.loop.run_until_complete(main())

你能帮我吗?我不明白为什么本地连接可以正常工作,但在docker容器中却不行

谢谢


Tags: thetofromimportclientidappawait

热门问题