telethon: Cannot cast TelegramClient to any kind of Peer报错的一个原因解释

参考文档:
telethon send_file
What is an Entity?
在使用telethon发送文件的时候遇到这个报错:

Cannot cast TelegramClient to any kind of Peer

第一个需要判断异步是否用对了,可以参考文档,假设写了一个方法来上传文件,方法名为getFileMsg,即使用client.loop.run_until_complete(getFileMsg())来调用方法,方法名前加async前缀。
在确定调用没错后,很有可能是实体(entity)出错了.
查阅文档,可以看到上传文件的send_file第一个参数就是entity,对entity的解释是:

entity (entity):
Who will receive the file.

于是去文档中搜索对entity的具体定义:

There are a lot of things that work as entities: usernames, phone numbers, chat links, invite links, IDs, and the types themselves. That is, you can use any of those when you see an “entity” is needed.

也就是说,可以用用户名,手机号,聊天连接等等~
但是这里注意,手机号是要加区号的完整手机号,例如 “+852xxxxxxxxxx”

当entity替换为正确的entity后,即可使用。以下是一个完整的可用demo:

import python_socks
from telethon import TelegramClient

# Remember to use your own values from my.telegram.org!
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
# 假设使用http 代理
# client = TelegramClient('mybot', api_id, api_hash,
#                         timeout=14, proxy=("http", "127.0.0.1", 10809))
# proxy = ('http', '127.0.0.1', 10809)

# client = TelegramClient('mybot', api_id, api_hash,
#                         timeout=10, proxy=("socks5", '127.0.0.1', 10808))

# client = TelegramClient('mybot', api_id, api_hash,
#                         timeout=10, proxy=(python_socks.ProxyType.SOCKS5, '127.0.0.1', 10808))

client = TelegramClient('mybot', api_id, api_hash,
                        timeout=10, proxy=(python_socks.ProxyType.HTTP, '127.0.0.1', 10809))


async def main():
    # Getting information about yourself
    me = await client.get_me()

    # "me" is a user object. You can pretty-print
    # any Telegram object with the "stringify" method:
    print(me.stringify())

    # When you print something, you see a representation of it.
    # You can access all attributes of Telegram objects with
    # the dot operator. For example, to get the username:
    username = me.username

    print(username)
    print(me.phone)


async def sendFileMsg():
    await client.send_file("+852xxxxxxxxx", 'test.txt', voice_note=True)


async def getFileMsg():
    path = await client.download_media()
    await client.download_media('test.txt')


with client:
    client.loop.run_until_complete(getFileMsg())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值