[英]Read message with group name telethon (telegram)
I have 10 groups in telegram with different name.我有 10 个不同名称的电报组。 I am able to print message with the below example code from telethon library.
我可以使用来自 Telethon 库的以下示例代码打印消息。 I also need the group name to be printed.
我还需要打印组名。
EG: G10001 Bhuvan Testing (GroupName UserName/Phoneno Message) EG:G10001 Bhuvan 测试(组名用户名/电话消息)
#!/usr/bin/env python3
# A simple script to print some messages.
import os
import sys
import time
from telethon import TelegramClient, events, utils
def get_env(name, message, cast=str):
if name in os.environ:
return os.environ[name]
while True:
value = input(message)
try:
return cast(value)
except ValueError as e:
print(e, file=sys.stderr)
time.sleep(1)
session = os.environ.get('TG_SESSION', 'printer')
api_id = get_env('TG_API_ID', 'Enter your API ID: ', int)
api_hash = get_env('TG_API_HASH', 'Enter your API hash: ')
proxy = None # https://github.com/Anorov/PySocks
# Create and start the client so we can make requests (we don't here)
client = TelegramClient(session, api_id, api_hash, proxy=proxy).start()
# `pattern` is a regex, see https://docs.python.org/3/library/re.html
# Use https://regexone.com/ if you want a more interactive way of learning.
#
# "(?i)" makes it case-insensitive, and | separates "options".
@client.on(events.NewMessage(pattern=r''))#pattern=r'(?i).*\b(hello|hi)\b'))
async def handler(event):
sender = await event.get_sender()
#client.get_input_entity(PeerChannel(fwd.from_id))
#channel = await event.get_channel()
#group = event.group()
#group = event.get_group()
#print(group)
#print(utils.get_peer_id(sender))
#print(utils.get_input_location(sender))
#print(utils.get_input_dialog(sender))
#print(utils.get_inner_text(sender))
#print(utils.get_extension(sender))
#print(utils.get_attributes(sender))
#print(utils.get_input_user(sender))
name = utils.get_display_name(sender)
print(name, 'said', event.text, '!')
#print(utils.get_input_entity(PeerChannel(sender)))
#print(utils.get_input_channel(get_input_peer(channel)))
try:
print('(Press Ctrl+C to stop this)')
client.run_until_disconnected()
finally:
client.disconnect()
# Note: We used try/finally to show it can be done this way, but using:
#
# with client:
# client.run_until_disconnected()
#
# is almost always a better idea.
I also need help to send message to groups.我还需要帮助向群组发送消息。 I have gone through some answer given below, which doesn't working for me.
我已经经历了下面给出的一些答案,这对我不起作用。
( Sending Telegram messages with Telethon: some entity parameters work, others don't? ) ( 使用 Telethon 发送 Telegram 消息:某些实体参数有效,其他的无效? )
First get the chat from incoming event:首先从传入事件中获取聊天:
chat = await event.get_chat()
Print group name:打印组名:
try:
if chat.title:
print(chat.title)
except AttributeError:
print('no such attribute present')
Send message to group:发送消息到组:
await client.send_message(entity=chat.id,message='hi')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.