How to forward every channels updates using Telethon - python

I would like to forward every updates from channels to my bot.
Is it Possible with ForwardMessagesRequest ?
I tried to use this Telethon example to build my personal code:
https://github.com/LonamiWebs/Telethon/wiki/Forwarding-messages
But i wasn't able to do it. And i don't know if it's possible to use that part of code inside a callback function. Someone can help me? Thank you

Ok, i'm really confused so let's go back.
In this code I just try to retrieve last messages from an user chat and forward them to my bot:
def callback(update):
source_chat_id = "here i put the user id"
source_hash = "here i put his access_hash"
source_chat = InputPeerUser(source_chat_id, source_hash)
total_count, messages, senders = client.get_message_history(
source_chat, limit=10)
for msg in reversed(messages):
print ("msg:", msg.id, msg)
msg = messages[0]
print ("msg id:", msg.id)
dest_chat = "here i tried to put the number of my bot ID"
result = client.invoke(ForwardMessagesRequest(from_peer=source_chat, id=[msg.id], random_id=[generate_random_long()], to_peer=dest_chat))
client.add_update_handler(callback)
The print was correct but i didn't receive anything to my bot chat.
I know that there will be a lot of errors so please be patient and sorry.

Related

Is there a way to access every website's data through discord.py

Hi stalkers
Is there a way to access a site's data directly?
I need it for my code :
#commands.command(aliases = ['isitsafe','issafe','scanlink'])
async def isthissafe(self, ctx, link: str):
try:
link = 'https://transparencyreport.google.com/safe-browsing/search?url='+ link.replace('/','%2F')
embed=discord.Embed(
color = discord.Color.dark_red(),
title = '',
description = f"[Transparency Report verification]({link})")
await self.emb(embed, ctx.author.name, 'https://cwatch.comodo.com/images-new/check-my-site-security.png')
await ctx.send(embed=embed)
except:
await ctx.send('An error has occured')
print('\nERROR')
Basically I made, a command which should tell if a link is safe or not, I did it using google's verification report site, but.. the problem is I only reformatted the link so the bot sens it in an embed and you access it from there.
My question is, now that you understood what I need, is there some way in which I could directly let the bot output the message from the website that indicates if the site is malicious/safe ??
Please help me.
I provided an image as well with the message I want to get from the site.
You might want to try scraping the site with bs4, or just look for the string "No unsafe content found". However, it looks like google populates the field based on a request.
Your best bet would be to use transparencyreport.google.com/transparencyreport/api/v3/safebrowsing/status?site=SITE_HERE. It returns a JSON response, but I don't understand it, so play around and figure out what the keys mean

Discord-Bot fails to message Users

I'm currently working on a bot that, messages Users in a given json-file in certain time intervals. I tried this code but it doesn't do what it's supposed to nor does it give me an error I could work with.
#tasks.loop(seconds=10)
async def dm_loop():
with open("users.json" "r") as file:
users = json.load(file)
for stgru in users:
for i in users[stgru]:
user = await client.fetch_user(i)
await user.send("hello")
And just in case you're wondering: the short time Intervals and the unnecessary message: "hello", ist just for testing purposes. The "users.json"-file, mentioned in the code, has a format like this:
{
"724": ["name1#2819", "name2#2781", "name3#2891"],
"727": [],
"986": ["name4#0192"],
"840": ["name5#1221", "name6#6652"],
"798": ["name7#3312", "name8#8242", "name9#1153", "name10#3318"]
}
I already added the "dm_loop.start()"-method to my "on_ready()" but it's not working at all.
I'd be so glad if anyone could help me out here. Thanks
According to the docs, fetch_user looks up users by their ID, so you need to store the user ID instead of the user name.
https://discordpy.readthedocs.io/en/master/ext/commands/api.html?highlight=fetch_user#discord.ext.commands.Bot.fetch_user
Otherwise you can create your own UserConverter. Here's an example on how you would do that.
from discord.ext import commands
[...]
user_name = "some_tag#1234"
user = await commands.converter.UserConverter().convert(ctx, argument=user_name)
await user.send("Hello")
I do really recommend the first option though, it is a lot simpler. Since you would have to create a custom context if you are not using this in a command i believe.

discord python bot api call with input error?

I'm trying to use an api call with user input and I have got an error that hasn't been solved in about 30 minutes of trying. I'm completely stuck, I used an api call before but without user input (showed bitcoin current price) and it worked perfect so I'm not sure what has gone wrong here.
If you can fix this, it would be very grateful, but if possible also explain what was wrong so I'll learn for next time thanks.
#client.command()
async def ipinfo(ctx, ip):
url = ('http://ip-api.com/json/' + ip)
response = requests.get(url)
country = response.json()['country']
city = response.json()['city']
embed = discord.Embed(color=discord.Color.red(), title="IP info for " + ip)
embed.add_field(name="Country", value=f'{country}', inline=False)
embed.add_field(name="City", value=f"{city}", inline=False)
await ctx.send(embed=embed)
I can provide the error message I get if needed, thanks for any help!
i worked it out i needed to add ip and ipinfo as aliases thank you.

How to send a random string via Inline Telegram commands?

I have created a bot (using python-telegram-bot) that upon choosing a type of query, the bot should randomly choose one of the available strings as the reply.
My function to create replies is as follows:
def generate_reply():
replies = """
Hello
Goodbye
Thanks!
Your welcome!
See you around!""".splitlines()
r = random.choice(replies).strip()
return r
And the functions to reply to the users are as follows:
#Inline Reply
def inlinequery(update, context):
query = update.inline_query.query
results = [InlineQueryResultArticle(id=uuid4(), title="Interact",
input_message_content=InputTextMessageContent(
generate_reply()))]
update.inline_query.answer(results)
#Normal reply
def reply(update, context):
update.message.reply_text(generate_reply())
And after creating the bot I add it to the bot using:
dp.add_handler(CommandHandler("reply", reply))
dp.add_handler(InlineQueryHandler(inlinequery))
when I use /reply in chat it works as intended, but wherever I use an inline command in a chat with another user or a group, the random choice apparently stops working.How can I get around this problem?
I found out the answer to my question. Apparently Telegram caches the answers to similar inline queries for some time. For this to work correctly you should set cache_time to something you'd like, in my case 0.
#Inline Reply
def inlinequery(update, context):
query = update.inline_query.query
results = [InlineQueryResultArticle(id=uuid4(), title="Interact",
input_message_content=InputTextMessageContent(
generate_reply()))]
update.inline_query.answer(results, cache_time=0)

Telegram bot API: get message id to forward it

So, I need my bot to forward a message of a chat. But in order to do so, I need to get the id of the message I want to forward (it's an old message). How can I get the id of that message so I can send it?
This is the code I'm using
#bot.message_handler(func=lambda m: True)
def reply_ids(message):
cid = message.chat.id
bot.reply_to(message, "The message id is: " + str(message.message_id) + " This chat ID is: " + str(cid))
When receiving a message, the id will be in message.message_id, as documented here.
If it is a supergroup or a channel, you can get the message_id by clicking on the message (in telegram web ) then choosing copy message link. the link will be in this form "https://t.me/channel_name/message_id"
This solution is to find the message_id manually!!
Recently I've been working with callback queries from inline buttons. One things I noticed is that in order to reply to the exact message that had the buttons Telegram needs to know both message.chat_id and message.message_id. You can try with both. This is more a comment then an answer but I don't have enough reputation to comment.
UPDATE: Now, It's update.message.message_id
Using python, if you have a CommandHandler() you can read the chat_id and message_id like so:
https://stackoverflow.com/a/72433953/1000741

Categories