discord python bot api call with input error? - python

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.

Related

Exporting specific json data from api with python

First time here, I am making a small discord.py bot as a project to experiment with python/apis a little. My goal is to print in discord specific data from an api when asked. here is the code in question.
#client.command()
async def otherusers(ctx, player):
rs = requests.get(apiLink + "/checkban?name=" + str(player))
if rs.status_code == 200:
rs = rs.json()
embed = discord.Embed(title="Other users for" + str(player), description="""User is known as: """ + str(rs["usedNames"]))
await ctx.send(embed=embed)
here is an example of the API request
{"id":1536171865,"avatar":"https://secure.download.dm.origin.com/production/avatar/prod/userAvatar/41472001/208x208.PNG","name":"_7cV","vban":{"A1 Army of One":{"bannedUntil":null,"reason":"ping >1000"}},"ingame":[],"otherNames":{"updateTimestamp":"2022-07-08T10:10:50.939000","usedNames":["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"]}}
If I change the string to str(rs["otherNames"]) it does function but I would like to only include the usernames, if I put str(rs["usedNames"]) and request on discord it gives me an error on PyCharm.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'usedNames'
Thanks in advance :)
Alright so as far as I can tell, the return from your API request where the "usedNames" key is located is nested. Try:
str(rs["otherNames"]["usedNames"])
I should note this will return ["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"] in the example which you gave. You might want to format the list of other usernames for your final product.
I hope that helped:)

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

How do I get a discord bot to send a random message inside an embed in python

So I wanted to use a command that puts a random message inside of an embed that also has a random gif attached to it, here is the code I'm using:
roastgifs = [
'https://tenor.com/view/roasted-oh-shookt-gif-8269968'
]
#client.command(aliases=['Roast'])
async def roast(ctx, member : discord.Member):
global roasting
global sus
roasting = [line.strip() for line in open('jokes.txt')]
sus = random.choice(roasting)
embed=discord.Embed(title=f"{ctx.author.mention} roasts {member.mention}\n\"" + sus + "\"")
roastgif=random.choice(roastgifs)
embed.set_image(url=roastgif)
embed.set_footer("footer")
await ctx.send(embed=embed)
I can't find that many tutorials on yt and Google and even then they're probably js and not py so I resorted to coming here again.
Also I would greatly appreciate how to make the bot ping someone with an ID if that's alright.
Embed.set_footer takes only keyword arguments, and you're passing a positional argument
embed.set_footer(text="Footer")
Also a few things:
You cannot ping in the embed title/footer (and somewhere else too, don't remember where atm)
The gif won't load. You only can add pictures in Embed.set_image
Reference:
Embed.set_footer
Embed.set_image

How to forward every channels updates using Telethon

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.

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