I'm trying to make a telegram bot with python but when I import telebot library (I have installed pyTelegramBotAPI & telebot libraries), but some parts don't work, like message_handler(), .reply_to() and .infinity_polling().
What could be causing this problem?
import telebot
import constant
from datetime import datetime
BOT_TOKEN = constant.api_key
bot = telebot.TeleBot(BOT_TOKEN)
#bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
#bot.message_handler(commands=['help'])
def send_welcome(message):
bot.reply_to(message, "you can ask me datetime and hi to me and ask who am i and how am i")
#bot.message_handler(func=lambda message: True)
def javab(in_text):
user_mess = str(in_text).lower()
if user_mess in ('hi','hello','sup'):
bot.reply_to(user_mess, "hi bro wtf do u want")
if user_mess in ('time','what time is it?','time?'):
now = datetime.now()
date_time = now.strftime("%d/%m/%Y,%H:%M:%S")
bot.reply_to(user_mess, str(date_time))
if user_mess in ('who are u','who are you?','you?'):
bot.reply_to(user_mess, 'non of your business , im hironside')
if user_mess in ('how are u?','how are you?'):
bot.reply_to(user_mess, 'im good')
if user_mess in ('/stop'):
return 'ok good bye'
else:
bot.reply_to(user_mess, 'go fly a kite')
print('bot is runnig ......')
bot.infinity_polling(5)
Related
Hi i want for my comment which will send 3 embeds and an Button when you click on the Button that you get the role "weeb"
(btw im starting bot coding im not a pro and i understand only the basics even when you can call these "basics")
btw the string text is german because it will be for a german server
The class with the Button:
import discord
from discord import ComponentInteraction
from discord.ext import commands
class RuleAcceptButton(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.on_click(custom_id='rule-accept-btn')
async def button1(self, ctx: ComponentInteraction, _):
role_id = 1046854949373489203
def setup(bot):
bot.add_cog(RuleAcceptButton(bot))
The class with the setup command:
#commands.Cog.slash_command(base_name='setup', name='rules', description='Send a Embed of the Rules')
async def setup_rules(self, ctx):
embed_rules_1 = discord.Embed(description='sample text'
embed_rules_1.set_author(name='§1 – Allgemeine Regeln')
embed_rules_1.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
embed_rules_2 = discord.Embed(colour=16711680, description='sample text'
# ab hier Embed2
embed_rules_2.set_author(name='§2 – Zusätzliche Regeln für Voice-Chats/Voice-Channels')
embed_rules_2.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
# ab hier Embed3
embed_rules_3 = discord.Embed(colour=16711680, description='sample text'
embed_rules_3.set_author(name='§3 – Zusätzliche Regeln für den Chat.')
embed_rules_3.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
await ctx.respond(embed=embed_rules_1)
await ctx.respond(embed=embed_rules_2)
await ctx.respond(embed=embed_rules_3, components=[
discord.Button(label='Accept Rules', custom_id='rule-accept-btn',style=discord.ButtonStyle.green)
i simply searched the whole internet and i didnt found anything
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 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))
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)