I need help with this code.
A month ago, I modified it to fit with me.
since three days, I suffer from an error that I could not fix .. He used to work before and now no
Thank you so much.
This is the source of the project
I have just modified the previous mistakes
I'm a beginner with only a month and a half experience
https://github.com/P-Alban/Telegram-collector
import sys
from getpass import getpass
from time import sleep
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.errors import UsernameNotOccupiedError
from telethon.errors import FloodWaitError
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import ChannelParticipantsSearch, InputChannel
# First you need create app on https://my.telegram.org
api_id = api_id
api_hash = 'api_hash'
phone = '+....Phone'
limit = 100
def get_chat_info(username, client):
try:
chat = client(ResolveUsernameRequest(username))
except UsernameNotOccupiedError:
print('Chat/channel not found!')
sys.exit()
result = {
'chat_id': chat.peer.channel_id,
'access_hash': chat.chats[0].access_hash
}
return result
def dump_users(chat, client):
counter = 0
offset = 0
chat_object = InputChannel(chat['chat_id'], chat['access_hash'])
all_participants = []
print('Process...')
while True:
participants = client.invoke(GetParticipantsRequest(
chat_object, ChannelParticipantsSearch(''), offset, limit
))
if not participants.users:
break
all_participants.extend(['{} {}'.format(x.id, x.username)
for x in participants.users])
users_count = len(participants.users)
offset += users_count
counter += users_count
print('{} users collected'.format(counter))
sleep(2)
with open('users.txt', 'w') as file:
file.write('\n'.join(map(str, all_participants)))
def main():
channel_name = input('Input a channel name, without "#": ')
client = TelegramClient(phone, api_id, api_hash)
print('Connecting...')
client.connect()
if not client.is_user_authorized():
try:
client.send_code_request(phone)
print('Sending a code...')
client.sign_in(phone, code=input('Enter code: '))
print('Successfully!')
except FloodWaitError as FloodError:
print('Flood wait: {}.'.format(FloodError))
sys.exit()
except SessionPasswordNeededError:
client.sign_in(password=getpass('Enter password: '))
print('Successfully!')
dump_users(get_chat_info(channel_name, client), client)
print('Done!')
if __name__ == '__main__':
main()
Related
At the moment, I was implementing a system using telethon and telebot, you yourself understand - an error occurs with thread, this option does not suit me, is there any other way to check an account by phone number? Or what can replace telethon? I tried in pyrogram - I could not figure it out. I would be grateful if you send the code / tell me what can be used.
Here is the implementation of my code
#Telegram Bot Library
import telebot
from telebot import types
import random
import requests as req
from bs4 import BeautifulSoup
#Telegram Library
from telethon.sync import TelegramClient
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser, InputPhoneContact
import configparser
cpass = configparser.RawConfigParser()
cpass.read('config.data')
try:
api_id = cpass['cred']['id']
api_hash = cpass['cred']['hash']
phone = cpass['cred']['phone']
client = TelegramClient(phone, api_id, api_hash)
except KeyError:
print("[!] для начала заполните все поля в config.data")
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('[+] введите код от телеграмм : '))
token = ""
bot = telebot.TeleBot(token)
user_data= {
'number': ''
}
#bot.message_handler(commands=['start', 'go'])
def start_handler(message):
msg = bot.send_message(message.chat.id, 'Здравствуйте! Я создан специально для sexcall.su.\nНапишите номер телефона пользователя :')
bot.register_next_step_handler(msg, user_number)
def user_number(message):
user_data['number'] = message.text
msg = bot.send_message(message.chat.id, 'Отлично, происходит проверка аккаунта, требуется ввести капчу:')
bot.register_next_step_handler(msg, getresults)
def getresults(message):
#Checking the received number via telethon
contact = InputPhoneContact(client_id=0, phone={user_data['number']}, first_name="custom_first_name", last_name="custom_last_name")
result = client(ImportContactsRequest([contact]))
#if the account is not found - display a message
if not client.get_entity({user_data['number']}):
bot.send_message(message.chat.id,"К сожалению, у данного пользователя нет телеграмма, пожалуйста, введите номер телефона : ")
#bot.register_next_step_handler(msg, number)
#If the account is found, execute the following code
else:
url = 'http://******/ocean/oceansite_balance.php?to=%s' % ({user_data['phone']})
resp = req.get(url)
soup = BeautifulSoup(resp.text, 'lxml')
if int(soup.p.string.strip()) == 0:
bot.send_message(message.chat.id,"К сожалению, у данного пользователя не достаточно средств, пожалуйста, введите номер телефона : ")
#bot.register_next_step_handler(msg, number)
bot.infinity_polling()
i am searching for a solution. I hava a bot which post by /start command some stuff i need. But id like that the bot do this in a defined time, maybe every 6h.
Hope someone could help me.
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from tracker import get_prices
telegram_bot_token = "xxx-xxx"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
chat_id = update.effective_chat.id
message = ""
crypto_data = get_prices()
for i in crypto_data:
coin = crypto_data[i]["coin"]
price = crypto_data[i]["price"]
change_day = crypto_data[i]["change_day"]
change_hour = crypto_data[i]["change_hour"]
message += f"Coin: {coin}\nPrice: ${price:,.2f}\nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
context.bot.send_message(chat_id=chat_id, text=message)
dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()
I was testing something an could add an timer, but is there a way to loop the programm with while True: ?
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from tracker import get_prices
import threading
import time
telegram_bot_token = "xxx:xxx"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def message_timer(update, context):
time.sleep(10)
chat_id = update.effective_chat.id
message = ""
crypto_data = get_prices()
for i in crypto_data:
coin = crypto_data[i]["coin"]
price = crypto_data[i]["price"]
change_day = crypto_data[i]["change_day"]
change_hour = crypto_data[i]["change_hour"]
message += f"Coin: {coin}\nPrice: ${price:,.2f}\nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
context.bot.send_message(chat_id=chat_id, text=message)
dispatcher.add_handler(CommandHandler("start", message_timer))
updater.start_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))
I have the basic code for sending a photo and i seem to understand the concept of choosing a random one. My question is where in this code should i put the random choice code?
import sys
import time
import os
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
import random
def on_chat_message(msg):
global chat_id
content_type, chat_type, chat_id = telepot.glance(msg)
#creating buttons
if content_type == 'text':
if msg['text'] == '/start':
bot.sendMessage(chat_id, 'Welcome to randomImgBot\nOn each click i will display you a random image of your choice\n Created by JonSnow 2021',reply_markup = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="PGP",callback_data='a')]]))
def on_callback_query(msg):
global chat_id
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
print('Callback Query:', query_id, from_id, query_data)
if query_data == 'a':
bot.sendPhoto(chat_id, photo=open('lolly.png'))
bot = telepot.Bot('')
MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_as_thread()
print('Listening ...')
while 1:
time.sleep(10)
Hi I'm trying to leave a channel with id with this script but it not showing any results well LeaveChannelRequest doesn't worked for me too
here is what i tried:
import asyncio
import logging
import re
import time
import os
import sys
import requests
logging.basicConfig(level=logging.ERROR)
from telethon import TelegramClient, events
from telethon.tl.functions.channels import LeaveChannelRequest
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.messages import GetBotCallbackAnswerRequest
from datetime import datetime
from colorama import Fore, init as color_ama
color_ama(autoreset=True)
os.system('cls' if os.name=='nt' else 'clear')
# my.telegram.org values, get your own there
api_id = ''
api_hash = ''
input_channel = '-1001226909513'
def print_msg_time(message):
print('[' + Fore.YELLOW + f'{datetime.now().strftime("%H:%M:%S")}' + Fore.RESET + f'] {message}')
async def main():
if len(sys.argv) < 2:
print('Usage: python start.py phone_number')
print('-> Input number in international format (example: +10123456789)\n')
e = input('Press any key to exit...')
exit(1)
phone_number = sys.argv[1]
if not os.path.exists("session"):
os.mkdir("session")
client = TelegramClient('session/' + phone_number, api_id, api_hash)
await client.start(phone_number)
me = await client.get_me()
print(Fore.GREEN + f' Current account: {me.first_name}({me.username})\n' + Fore.RESET)
print_msg_time('leaving channels')
async def main():
await client.delete_dialog(input_channel)
print_msg_time(f'{input_channel} has been leaved')
asyncio.get_event_loop().run_until_complete(main())
where is my problem?
The method call to leave the channel or group is defined in inner function
[...]
print_msg_time('leaving channels')
async def main():
await client.delete_dialog(input_channel)
print_msg_time(f'{input_channel} has been leaved')
which isn't called in outer function, you could avoid using a inner function. for example, you can call delete_dialog method like this
[...]
print_msg_time('leaving channels')
await client.delete_dialog(input_channel)
print_msg_time(f'{input_channel} has been leaved')