可查閱telegram文檔
安裝
pip3 install --upgrade telethon
到https://my.telegram.org/用手機號登錄這個網址申請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) #代理設置
).start()
#此處的some_name是一個隨便起的名稱,第一次運行會讓你輸入手機號和驗證碼,之后會生成一個some_name.session的文件,再次運行的時候就不需要反復輸入手機號驗證碼了
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) #代理設置
).start()
給自己發送一條消息/文件
client.send_message('me', 'Hello! Talking to you from Telethon')
client.send_file('me', '/home/shanghaimei/Pictures/images.png')
獲取自己發送的上一條信息
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!')
某個人的信息
peer = client.get_input_entity('@HuingZM')#可更換用戶名
peer = utils.get_input_peer(peer)
print(peer)
打印信息#InputPeerUser(user_id=1234556, access_hash=-5728264861981944)
給特定的人和頻道發送信息
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,"這是一個頻道",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,"這是一個用戶",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,'這是一個機器人',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)
邀請人進群組
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
))
邀請人進頻道
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,"這是一個頻道",dict_channel_info)
channel = client.get_entity(PeerChannel(channel_id)) # 根據群組id獲取群組對
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) #防止出現UserPrivacyRestrictedError
轉發信息
messages = client.get_messages('china_BiBi')#括號參數為來源頻道username,因為要獲取信息id
mes_id = messages[0].id
client.forward_messages(1219921340,mes_id,1182116619)
#第一個參數為目標頻道id,第二個信息id,第三個來源頻道id
實時轉發信息
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