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.
Related
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:)
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
I'm creating a Telegram Bot and I need to get file_id.for example, photos.
For example:
"AgACAgIAAx0CW7VwqQAD3GE80mUSC6AbGV2lcHFzI5J3me7zAAJwtTEbkWJISbKzPMDueHfrAQADAgADeAADIAQ"
Is there such a possibility and how can I do it?
If you need more information, ask. Thank you!
Telethon documentation shows what attributes Document and Photo have.
So you can use the following code:
#client.on(events.NewMessage())
async def downloader(event):
file = event.document or event.photo
file_id = file.id
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)
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.