I'm making a Telegram bot and I need to set a time range for collecting messages for the last month.
from telethon import TelegramClient
from datetime import date
api_id = my_id
api_hash = ''
phone = ''
client = TelegramClient(phone, api_id, api_hash)
dateStart = date(2022, 12, 27)
async def main():
async for message in client.iter_messages(-1001369370434, reverse=True, offset_date=dateStart, search='eth'):
print(message.chat.title, ':', message.date, ':', message.text)
with client:
client.loop.run_until_complete(main())
The offset_date should be the beginning of the date range.
Then use reverse=True to loop from the offset_date to today's latest message:
My complete test script:
import datetime
import asyncio
import re
from telethon import TelegramClient
CHAT = 1234567
BEGIN = datetime.datetime(2022, 11, 1, 0, 0, 0)
client = TelegramClient('anon', '111111', 'aaaabbbbccccddddeee')
client.start()
async def main():
chat = await client.get_input_entity(CHAT)
async for message in client.iter_messages(chat, reverse=True, offset_date=BEGIN):
print(message.date, "\t\t", message.text)
client.loop.run_until_complete(main())
Which output's all the messages starting 2022-11-1 until today:
2022-11-01 00:00:43+00:00 ...
2022-11-01 00:00:59+00:00 ...
2022-11-01 00:01:50+00:00 ...
2022-11-01 00:01:50+00:00 ...
2022-11-01 00:05:32+00:00 ...
2022-11-01 00:08:47+00:00 ...
2022-11-01 00:10:00+00:00 ...
Related
I have a problem. I want to send to a certian group chat every day at 06:00 a clock a message.
When I am calling my script it just send once a Hello and the other commands like \Greet does not work.
import os
import telebot
import requests
from telebot.async_telebot import AsyncTeleBot
import asyncio
import datetime
load_dotenv()
API_KEY = os.getenv('API_KEY')
#print(API_KEY)
bot = AsyncTeleBot(API_KEY)
#bot.message_handler(commands=['Greet'])
def greet(message):
bot.reply_to(message, "Hey! Hows it going?")
async def hello():
await bot.send_message(<chatid>, "Hello")
async def wait_until(dt):
# sleep until the specified datetime
now = datetime.datetime.now()
await asyncio.sleep(5)
async def run_at(dt, coro):
await wait_until(dt)
return await coro
loop = asyncio.get_event_loop()
# print hello ten years after this answer was written
loop.create_task(run_at(datetime.datetime(2028, 7, 11, 23, 36),
hello()))
loop.run_forever()
asyncio.run(bot.polling())
So i found this piece of code somewhere on stackoverflow:
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
from datetime import datetime
api_id = 123456789 #Enter Your 7 Digit Telegram API ID.
api_hash = '123456789' #Enter Yor 32 Character API Hash.
phone = '123456789'
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code recieved to your Telegram messenger: '))
chats = []
last_date = None
chunk_size = 200
groups=[]
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash = 0
))
chats.extend(result.chats)
for chat in chats:
try:
if chat.megagroup== True:
groups.append(chat)
except:
continue
print('Choose a group to scrape members from:')
i=0
for g in groups:
print(str(i) + '- ' + g.title)
i+=1
g_index = input("Enter a Number: ")
target_group=groups[int(g_index)]
print('Fetching Members...')
all_participants = []
all_participants = client.get_participants(target_group, aggressive=True)
print('Saving In file...')
with open("Scraped.csv","w",encoding='UTF-8') as f:
writer = csv.writer(f,delimiter=",",lineterminator="\n")
writer.writerow(['username','user id', 'access hash','name','group', 'group id','last seen'])
for user in all_participants:
accept=True
try:
lastDate=user.status.was_online
num_months = (datetime.now().year - lastDate.year) * 12 + (datetime.now().month - lastDate.month)
if(num_months>1):
accept=False
except:
continue
if (accept) :
if user.username:
username= user.username
else:
username= ""
if user.first_name:
first_name= user.first_name
else:
first_name= ""
if user.last_name:
last_name= user.last_name
else:
last_name= ""
name= (first_name + ' ' + last_name).strip()
writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id,user.status])
print('Members scraped successfully.')
And this pretty much scrapes online & recently active members, how would i change this to ONLY scrape online members? I tried looking into the telethon docs but i don't seem to understand...
I'm not sure where else to ask for help regarding this issue so here i am...
Any sort of help is highly appreciated!
Thank you.
Scraping ONLY online members is not possible.
Try something like this:
import telethon
from telethon.sync import TelegramClient, events
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import InputChannel
from telethon.tl.types import ChannelParticipantsSearch
from telethon.tl.functions.channels import GetFullChannelRequest
api_id = 123567
api_hash = "dsaopdas2131"
client = TelegramClient("RDJR", api_id, api_hash)
#client.on(events.NewMessage())
async def handler(event):
chat_id = event.message.peer_id.channel_id
offset = 0
limit = 200
my_filter = ChannelParticipantsSearch('')
channel = await client(GetFullChannelRequest(chat_id))
participants = await client(GetParticipantsRequest(channel=chat_id, filter=my_filter, offset=offset, limit=limit, hash=0))
for x in participants.users:
print(x.status)
with client as client:
print("USER_BOT ONLINE!")
client.run_until_disconnected()
You need to get all of the participants of a group/channel, then iterate them to print the status.
The output would be something like this:
User online:
UserStatusOnline(expires=datetime.datetime(2021, 7, 6, 21, 6, 22, tzinfo=datetime.timezone.utc))
Or:
None
User offline:
UserStatusOffline(was_online=datetime.datetime(2021, 7, 6, 18, 19, 35, tzinfo=datetime.timezone.utc))
Hello I'm using Telethon 1.21.1
The most question here are outdated.
This scripts task is to read a message of a specific Channel per id.
I'm not sure where to pass the info for the channel and how if I use the method to read the msg in the proper way. await but I'm not sure how I pull it off
This is what I have:
my_private_channel_id = "-100777000"
my_private_channel = "test"
api_id = # 7 Digit Telegram API ID.
api_hash = '' # 32 Character API Hash
phone = '+' #Enter Your Mobilr Number
client = TelegramClient(phone, api_id, api_hash)
async def main():
await client.send_message('me', 'Hello !!!!') # just to test connection
with client:
client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter verification code: '))
chats = []
last_date = None
chunk_size = 200
channels=[] #target channel
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash = 0
))
chats.extend(result.chats)
for chat in chats:
try:
if chat.channels== True:
readmsg = client.get_messages(chat, None)
except:
continue
from telethon import TelegramClient, events
client = TelegramClient('session', api_id, api_hash)
#client.on(events.NewMessage(chats="#TelethonUpdates"))
async def my_event_handler(event):
print(event.text)
client.start()
client.run_until_disconnected()
This is the right and simple way.
I want to make a discord bot that texts me every day when online classes begin.
import discord
from discord.ext import commands
from datetime import *
import discord.utils
from discord.utils import get
import pytz
local = datetime.now()
tbilisi = pytz.timezone("Asia/Tbilisi")
datetime_tbilisi = datetime.now(tbilisi)
Monday = "Monday"
dro1_saati = 9
dro1_wuti = 30
async def on_ready():
channel = discord.utils.get(client.guilds[0].channels, name = "general")
await client.change_presence(status = discord.Status.online, activity = discord.Game("with z.help_me | Aleksandre"))
#Monday
if Monday == datetime_tbilisi.strftime("%A") and dro1_saati == datetime_tbilisi.hour and dro1_wuti == datetime_tbilisi.minute:
embed = discord.Embed(title = "Monday", description = ": https://us04web.zoom.us/j/78382716896?pwd=RUxiZExKRHFadSszS01pZWk0WVNKQT09k\n ID:783 8271 6886 \n Pass:1010", colour = discord.Colour.blue())
await channel.send(embed = embed)
when I host it on Heroku, it is not working.
How can I get last posts and messages from all channel and groups in my Telegram account using "telethon".
At first you should get your "api_id" and "api_hash" from Telegram API.
then you should use following code to connect to your Telegram account.
from telethon.sync import TelegramClient
from telethon.errors import SessionPasswordNeededError
# Create the client and connect
client = TelegramClient(you_username, api_id, api_hash)
client.start()
print("Client Created")
# Ensure you're authorized
if not client.is_user_authorized():
client.send_code_request(your_phone)
try:
client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
client.sign_in(password=input('Password: '))
In the next step we define a def to get last message of an entity (like channel or group):
from telethon.tl.functions.messages import GetHistoryRequest
def get_entity_data(entity_id, limit):
entity = client.get_entity(entity_id)
today = datetime.datetime.today()
# y = today - datetime.timedelta(days=1)
posts = client(GetHistoryRequest(
peer=entity,
limit=limit,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
messages = []
for message in posts.messages:
messages.append(message.message)
return messages
This def gets id of a channel or group and limit on number of messages that we want to get from any channels and groups and returns the messages.
Then you should get all groups and channels using this code:
from telethon.tl.functions.messages import GetDialogsRequest
result = client(GetDialogsRequest(
offset_date=None,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=100,
hash=0))
entities = result.chats
And in last step you should iterate on entities and get last messages(for example 10 in following code)
for entity in entities:
title = entity.title
messages = get_entity_data(entity.id, 10)
print(title + ' :')
print(messages)
print('#######')