参考文档:
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())