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 <a href="https://t.me/haimei_group">BiBi'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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容