relayer.py
async def send_gift(username, gift_id=config.teddy_id):
client = TelegramClient(session_name, api_id, api_hash)
client.start(phone=config.phone, password=config.two_factor)
try:
receiver_peer = await client.get_input_entity(username)
print(receiver_peer)
invoice = InputInvoiceStarGift(
peer=receiver_peer,
gift_id=gift_id
)
print(f"Generated Invoice: {invoice}")
payment_form = client(functions.payments.GetPaymentFormRequest(invoice=invoice))
if payment_form:
print("Payment form retrieved successfully!")
payment_result = client(functions.payments.SendStarsFormRequest(
form_id=payment_form.form_id,
invoice=invoice
))
print(f"Payment successful: {payment_result.stringify()}")
except Exception as e:
print(f"An error occurred: {e}")
这是一个向指定用户名发送泰迪熊的函数。即使没有定义 send_gift() 函数,它也运行正常,但我需要让这个函数可以从其他脚本调用(relayer.py 永远不会作为main运行)。出现了“断开连接时无法发送请求”的问题。我怀疑我可能在这里错误地使用了 client.start() 函数。如有任何建议,我将不胜感激!
Asyncio 应该已经向您显示警告,必须在异步上下文中
await
执行 client.start(),因为事件循环已经在运行。另外,您传递给它的电话和密码在脚本上下文中是无用的,您应该事先登录帐户并创建会话,在这种情况下它们会被忽略。
所有 client() 调用也必须被
await
编辑。参考文档