telethon : How to search a keyword globally from telegram messages in python? - bots

So basically I want to search messages by a keyword irrespective of a member of that group/channel or not.
For example, in some group/channel of which I am not a member, there is a message-
"Hello, this is some information about banana"
and let's say I search keyword 'banana' then I should get the whole above message.
I wrote a script but it only searches the name of groups instead of messages.
from telethon import functions
import os, sys
try:
api_id = api_id
api_hash = api_hash
phone = phone
client = TelegramClient(phone, api_id, api_hash)
except KeyError:
os.system("clear")
print(re + "[!] run python3 setup.py first !!\n")
sys.exit(1)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
os.system("clear")
client.sign_in(phone, input(gr + "[+] Enter the code: " + re))
os.system("clear")
last_date = None
chunk_size = 200
results = client(
functions.contacts.SearchRequest(q="banana", limit=100)
)
print(results.stringify())

You can use client.iter_messages with the chat set as None to perform a global search:
async for message in client.iter_messages(None, search='banana'):
...
Underneath it's using SearchGlobalRequest .

Related

Python Telegram Bot Job won't get back on execution after network fluctuation

since my network at home is reconnecting every night, my computer is off internet for some seconds up to minutes.
When running my python telegram bot, it throws errors coming from urllib3 as
urllib3.exceptions.MaxRetryError: and requests as requests.exceptions.ConnectionError and telegram package error as telegram.error.NetworkError: urllib3 HTTPError
My programm is still able to run telegrams commandhandler tasks upon request in telegram, but the main job has stopped working. Any ideas how to get it working again?
For simplicity I created just this minimal example. The error can be easily induced by disconnecting from wifi or ethernet.
Dependent on where in the code the disconnect happens, the sequence of the error appearing might change.
import logging
from time import sleep
from yfinance import download as yfdownload
from telegram.ext import (
Updater,
CallbackContext,
)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
print = logger.info
stocklist = ["MSFT", "TSLA", "BABA", "DE", "BIDU", "FSLY", "REPYY", "CRWD", "NET", "AMD", "BNTX", "CRWD", "WING"]
def callback_minute(context):
checkStatus(context)
job_minute = context.job_queue.run_once(callback_minute, 10)
def checkStatus(context):
for ticker in stocklist:
while True:
try:
price = yfdownload(ticker, progress = False).iloc[-1]["Close"].round(3)
print("Current price for: " + ticker + " is: " + str(price))
break
except:
sleep(1)
continue
def error_handler(update: object, context: CallbackContext):
logger.error(msg="Exception while handling an update:", exc_info=context.error)
print("can I do something here ?")
def main():
token = "insert telegram token here"
updater = Updater(token, request_kwargs = {"read_timeout" : None, "connect_timeout" : None})
j = updater.job_queue
dispatcher = updater.dispatcher
dispatcher.add_error_handler(error_handler)
job_minute = j.run_once(callback_minute, when = 5)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()

Discord sends message more than expected

import requests
from bs4 import BeautifulSoup
from random import choice
import re, json
import discord
Bot = discord.Client()
def names():
asd = []
n = open("1", "wb")
url = 'aurl.com'
r = requests.get(url).text
a = json.loads(r)
for i in a.items():
asd.append(i[1]["baslik"])
return asd
#Bot.event
async def on_ready():
print(1)
list = names()
channel = Bot.get_channel(825744124485173298)
for i in list:
await channel.send(i)
Bot.run(key)
I want this bot to get dicts from 'aurl.com' site and send it. But following script send same dict more than one time. Where am i making mistake ?
The on_ready event has explicit documentation that states:
This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

python-telegram-bot error when in Channel

I just finished creating my first bot and it works perfectly in groups and when I message it, however, when I add it to a Channel and give it all permissions it does not work. The echo message function gives an error of caused error 'NoneType' object has no attribute 'text'.
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import MessageEntity, InlineQueryResultArticle, InputTextMessageContent
def echo(update, context): # this is from the documentation
context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
def error(update, context):
print(f'Error {update} caused error {context.error}')
def main():
updater = Updater(API)
dp = updater.dispatcher
#Echo message
echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dp.add_handler(echo_handler)
#Handle errors
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
main()
For channel posts it's update.channel_post not update.message.text. Alternatively, update.effective_message can be used if you don't want to differentiate between channel posts, messages and edited messages/channel posts.
def echo(update, context):
context.bot.send_message(
chat_id=update.effective_chat.id, text=update.effective_message)

my if statement on my discord bot seems to jump right to else even when given a number that is in my list

im trying to make a bot that responds with a random peace of text when someone types >test but i dont get any syntax errors but my number gen just goes to else in the if statement instantly :/
source code:
import discord
from discord.ext import commands
from secrets import randbelow
prefix = ">"
bot = commands.Bot(command_prefix = prefix)
#bot.event
async def on_ready():
print("i have connected to discord! ^-^")
#bot.command(pass_context = True)
async def test(ctx):
x = (randbelow(3))
if x =="1":
await ctx.send("Yay 1")
elif x =="2":
await ctx.send("Yay 2")
else:
print("fuck")
bot.run("my token")
randbelow() returns an integer, so do
if x == 1 and so on...

How can I transfer members of a Telegram channel to another Telegram channel

How can I transfer members of a Telegram channel (which I am their admin) or a group (or a super group) to another Telegram channel or group (which I am not their admin)?
Regards
You can use telethon its very easy and you have a lots of documentation out there.
For you specific question
from telethon.tl.functions.channels import InviteToChannelRequest
client(InviteToChannelRequest(
channel=SomeChannelId,
users = ['SomeUserName']
))
I have used telethon:
from telethon import TelegramClient
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.channels import GetParticipantsRequest
import asyncio
# Use your own values from my.telegram.org
api_id = 12345
api_hash = 'a1a1a1a1a1a1a11'
channel_to_name = 'migrate_to'
channel_from_name = 'migrate_from'
loop = asyncio.get_event_loop()
client = TelegramClient('anon', api_id, api_hash)
loop.run_until_complete(client.connect())
channel_from = loop.run_until_complete(client.get_entity(channel_from_name))
channel_to = loop.run_until_complete(client.get_entity(channel_to_name))
users = client.iter_participants(channel_from)
users_arr = []
for user in users:
users_arr.append(user)
loop.run_until_complete(client(InviteToChannelRequest(
channel_to,
users_arr
)))

Resources