可查閱telegram文檔
安裝
pip3 install --upgrade telethon
到https://my.telegram.org/用手機(jī)號(hào)登錄這個(gè)網(wǎng)址申請api
申請成功后保存好api_id和api_hash
連接客戶端
from telethon import TelegramClient, sync
import socks
# Use your own values here
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('some_name'
api_id,
api_hash,
proxy=(socks.SOCKS5, 'localhost', 4444) #代理設(shè)置
).start()
#此處的some_name是一個(gè)隨便起的名稱,第一次運(yùn)行會(huì)讓你輸入手機(jī)號(hào)和驗(yàn)證碼,之后會(huì)生成一個(gè)some_name.session的文件,再次運(yùn)行的時(shí)候就不需要反復(fù)輸入手機(jī)號(hào)驗(yàn)證碼了
myself = client.get_me()
print(myself) #測試是否連接
引入的包
from telethon import TelegramClient, sync,events
import logging
import random
import asyncio
import telethon
from telethon.tl.types import PeerUser, PeerChat, PeerChannel,UpdateNewChannelMessage
from telethon.tl.functions.messages import SendMessageRequest
from telethon.tl import types, functions
from telethon import utils
連接
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('some_name'
api_id,
api_hash,
proxy=(socks.SOCKS5, 'localhost', 4444) #代理設(shè)置
).start()
給自己發(fā)送一條消息/文件
client.send_message('me', 'Hello! Talking to you from Telethon')
client.send_file('me', '/home/shanghaimei/Pictures/images.png')
獲取自己發(fā)送的上一條信息
messages = client.get_messages('me')#可更改用戶名
print(messages[0].text)
可以自定義聊天
@client.on(events.NewMessage)
async def my_event_handler(event):
if 'hello' in event.raw_text:
await event.reply('hi!')
if 'what' and 'name' in event.raw_text:
await event.reply('Haimei_bot,Thanks!')
某個(gè)人的信息
peer = client.get_input_entity('@HuingZM')#可更換用戶名
peer = utils.get_input_peer(peer)
print(peer)
打印信息#InputPeerUser(user_id=1234556, access_hash=-5728264861981944)
給特定的人和頻道發(fā)送信息
result = client(SendMessageRequest('HuingZM', 'Hello there!'))
result = client(SendMessageRequest(PeerChannel(1182116619), 'Hello there!'))
print(result)
打印群信息
dialogs = client.get_dialogs()
# 打印群信息
print(client.get_entity("@hello")) #可更換群組名
打印頻道信息
my_channel = client.get_entity(dialog.title)
print(my_channel)
獲取全部的聊天信息
for message in client.iter_messages(1182116619):
print(message)
判斷列表信息
for dialog in client.iter_dialogs():
friend_info = client.get_entity(dialog.title) #dialog.title為first_name
if type(friend_info) is not telethon.tl.types.User:
channel_id = friend_info.id
channel_title = friend_info.title
channel_username = friend_info.username
dict_channel_info = {"channel_id":channel_id,"channel_title":channel_title,"channel_username":channel_username}
print(dialog.title,"這是一個(gè)頻道",dict_channel_info)
else:
if friend_info.bot is False:
user_id = friend_info.id
user_name = friend_info.username
is_bot = friend_info.bot
user_phone = friend_info.phone
dict_user_info = {'user_id':user_id,'user_name':user_name,'user_phone':user_phone,'is_bot':is_bot}
print(dialog.title,"這是一個(gè)用戶",dict_user_info)
else:
bot_id = friend_info.id
bot_name = friend_info.username
is_bot = friend_info.bot
dict_bot_info = {'bot_id':bot_id,'bot_name':bot_name,'is_bot':is_bot}
print(dialog.title,'這是一個(gè)機(jī)器人',dict_bot_info)
獲取頻道成員信息
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
from time import sleep
offset = 0
limit = 100
all_participants = []
while True:
participants = client(GetParticipantsRequest(
1387666944, ChannelParticipantsSearch(''), offset, limit, hash=0
))
if not participants.users:
break
all_participants.extend(participants.users)
for par in all_participants:
print(par)
邀請人進(jìn)群組
from telethon.tl.functions.messages import AddChatUserRequest
client(AddChatUserRequest(
chat_id = -269442445 , #chat_id
user_id = 585015279 , #被邀請人id
fwd_limit=10 # Allow the user to see the 10 last messages
))
邀請人進(jìn)頻道
from telethon.tl.functions.channels import InviteToChannelRequest
client(InviteToChannelRequest(
channel=1182116619, #頻道id
users = ['HuingZM'],#列表格式的username
))
獲取頻道成員信息并將成員加入自己的群組或頻道,并加入歡迎語
for dialog in client.iter_dialogs():
friend_info = client.get_entity(dialog.title) #dialog.title為first_name
if type(friend_info) is not telethon.tl.types.User:
channel_id = friend_info.id
channel_title = friend_info.title
channel_username = friend_info.username
dict_channel_info = {"channel_id":channel_id,"channel_title":channel_title,"channel_username":channel_username}
# print(dialog.title,"這是一個(gè)頻道",dict_channel_info)
channel = client.get_entity(PeerChannel(channel_id)) # 根據(jù)群組id獲取群組對(duì)
responses = client.iter_participants(channel, aggressive=True) # 獲取群組所有用戶信息
for response in responses:
if response.username is not None:
d = {'id':response.id,'username':response.username}
print(d)
time.sleep(2)
client(InviteToChannelRequest(
channel=1219921340,
users = [d.get('username')],
))
client.send_message(1219921340,'''?Welcome to <a s group</a> chat {} !'''.format(d.get('username')) ,parse_mode="html")
time.sleep(2)?。7乐钩霈F(xiàn)UserPrivacyRestrictedError
轉(zhuǎn)發(fā)信息
messages = client.get_messages('china_BiBi')#括號(hào)參數(shù)為來源頻道username,因?yàn)橐@取信息id
mes_id = messages[0].id
client.forward_messages(1219921340,mes_id,1182116619)
#第一個(gè)參數(shù)為目標(biāo)頻道id,第二個(gè)信息id,第三個(gè)來源頻道id
實(shí)時(shí)轉(zhuǎn)發(fā)信息
messages = client.get_messages('china_BiBi')
mes_id_1 = messages[0].id
while True:
messages = client.get_messages('china_BiBi')
mes_id = messages[0].id
if mes_id != mes_id_1:
client.forward_messages(1219921340,mes_id,1182116619)
mes_id_1 = mes_id