Telegram Client 开发

可查阅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 BiBi's group 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

你可能感兴趣的:(Telegram Client 开发)