im wondering if i could message more channels at once by id ( general, announcements, giveaways etc.)
This is my error right now but i cannot figure it out why is not working.
ERROR: Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 17, in on_ready
member = await bot.fetch_user(i)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 1384, in fetch_user
data = await self.http.get_user(user_id)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 250, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10013): Unknown User
and the code is in the pastebin:
Fetch
The problem is that you used fetch_user() instead of fetch_channel at line 17.
You should try to use this code:
channel = await bot.fetch_channel(i)
await channel.send("...")
Your error is that into your .json file there are some IDs, and they're channels' IDs.
Using channels' IDs like members' IDs will obviously raise an error.
In that case your error is saying that the member with the ID given to fetch_user() doesn't exist.
Suggestion
You should use exception handling to remove from the file the channels which are not still existing.
For example:
with open(r"C:\\Your\Path\to\file.json", 'r+') as File:
data = json.load(File)
for ID in data:
try:
channel = bot.fetch_channel(ID)
except discord.errors.NotFound: # Raised if ID doesn't exist anymore
data.remove(ID)
os.remove(r"C:\\Your\Path\to\file.json")
with open(r"C:\\Your\Path\to\file.json", 'w') as File:
json.dump(data, File)
DM users
If you want to DM some users from their IDs, you just have to do like this:
with open(r"C:\\IDs.json", 'r') as File:
data = json.load(File)
for ID in data:
user = await bot.fetch_user(ID)
await user.send("Your message")
Remember this can raise an exception, because some users don't allow bots to DM them.
Related
I'm coding a discord bot a for a friend using python (discord.py) and i've a specific task i want the bot to do that i can't figure out how to code (i'm kinda a newbie with py), so here it is: we use a specific text-channel to post wins of the games we play mentioning every partecipant, i want the bot to count every mention a user has in that channel and return me the number. Reading here and there i saw i should be using either message.raw_mentions or message.mentions but i don't know how to make it select the proper channel and how to just return the number of a specific user's mentions. So far the code looks like this:
async def testcommand(self, context: Context, user: discord.User) -> None:
member = context.guild.get_member(user.id) or await context.guild.fetch_member(user.id)
mentions = message.mentions
for user in mentions:
if user.id in ???????????
embed = discord.Embed(
title="**Wins:**",
description=f"{member}",
color=0x9C84EF
)
await context.send(embed=embed)
Thanks for your help, have a nice day!
UPDATE:
Code works now and looks like this:
async def testcommand(self, context: Context, user: discord.Member, channel: discord.TextChannel) -> None:
potato = 0
async for message in channel.history(limit=None):
if user in message.mentions:
potato += 1
embed = discord.Embed(
title="**Test:**",
description=f"{potato}",
color=0x9C84EF
)
await context.send(embed=embed)
Problem is doesn't fetch from channels that are too rich of messages, i get this error:
2022-12-09 14:52:26 ERROR discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 861, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Gianvito\Desktop\dts_bot\cogs\template.py", line 44, in testcommand
await context.send(embed=embed)
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\context.py", line 876, in send
await self.interaction.response.send_message(**kwargs)
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'testcommand' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Gianvito\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Gianvito\Desktop\dts_bot\bot.py", line 201, in on_command_error
raise error
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'testcommand' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
I've read somewhere that could be the discord API that requires a feedback in a span of time (2 or 3 seconds) that doesn't get, i supposed, cause the bot requires more time to fetch a big channel.
Maybe something like this, where it iterates over every message sent in the current channel?
#bot.command()
async def some_command(ctx):
mentions = 0
async for message in ctx.channel.history(limit=10000000): # set limit to some big number
if ctx.author in message.mentions:
mentions += 1
await ctx.send(mentions)
The above code counts the number of times the author is mentioned in the current channel.
Of course, this is highly inefficient, but it gets the job done.
If you wish to add more parameters (such as the user and the channel):
#bot.command()
async def better_command(ctx, user: discord.Member, channel: discord.TextChannel):
mentions = 0
async for message in channel.history(limit=10000000): # set limit to some big number
if user in message.mentions:
mentions += 1
await ctx.send(mentions)
Here is my code:
from discord.ext import commands
import os
import discord
import requests
import json
my_secret = os.environ['MY_TOKEN']
GUILD = os.getenv('DISCORD_GUILD')
bot = commands.Bot(command_prefix='!') #prefix
discord.CustomActivity("Jaxon\'s brain melt", ActivityType="watching", emoji=None)
#bot.command(name="enfr", help="Translates text from english to french")
async def enfr(ctx, text):
response = requests.get("https://api.mymemory.translated.net/get?q=" + text + "&langpair=en|fr")
json_data = json.loads(response.text)
translation = json_data.get("translatedText") + "test"
print(response.status_code)
await ctx.channel.send(translation)
bot.run(my_secret)
This is the error I get:
200
Ignoring exception in command enfr:
Traceback (most recent call last):
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 22, in enfr
await ctx.channel.send(translation)
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/translate-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
It worked a few days ago and now it doesn't :(
There is one other command, but it doesn't don't affect this one so I removed it from the code to clear it up a bit. I get that error when I try to run the command !enfr hello
I don't know if this is the correct place to ask, my last questions were disliked by some people.
The traceback specifies the error is Cannot send an empty message. Specifically:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
Looking at it more closely you can find the line of your file where the Exception is being thrown.
File "main.py", line 22, in enfr await ctx.channel.send(translation)
From these it seems quite clear that translation is None or an empty string, and that the function ctx.channel.send throws an Exception when that is the case.
Now try to figure out why translation is empty by reviewing how you're creating it in the first place, and account for these edge-cases.
Note: Reading traceback logs might seem daunting at first, but they're quite informative (at worst showing you where in your code the issue is). Don't panic and just go through them slowly :)
I'm trying to get a user's ID via a message ID; the ID of the user I want to send a DM to is in the embed's footer. I'm using this code for it:
msg = await ctx.channel.fetch_message(id)
id2 = int(msg.embeds[0].footer.text)
print(type(id2))
await ctx.send(id2, hidden=True)
# Everything works fine ^
# Everything breaks below
user = client.get_user(id2)
print(type(user))
await ctx.send(user, hidden=True)
await user.send("IT WORKED!!!")
I added some debugging code and it appears to break when it tries to convert it to a user in user = client.get_user(id2). It converts it into nothing; I saw that with the type() function, and in the error:
An exception has occurred while executing command `answer`:
Traceback (most recent call last):
File "/Users/dante_nl/Library/Python/3.8/lib/python/site-packages/discord_slash/client.py", line 1185, in invoke_command
await func.invoke(ctx, **args)
File "/Users/dante_nl/Library/Python/3.8/lib/python/site-packages/discord_slash/model.py", line 209, in invoke
return await self.func(*args, **kwargs)
File "/Users/dante_nl/Library/Mobile Documents/com~apple~CloudDocs/Ask/bot.py", line 105, in _answer
await ctx.send(user, hidden=True)
File "/Users/dante_nl/Library/Python/3.8/lib/python/site-packages/discord_slash/context.py", line 239, in send
resp = await self._http.post_followup(base, self._token, files=files)
File "/Users/dante_nl/Library/Python/3.8/lib/python/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
I'm not sure why it does this, it got the ID from the embed's footer, converted it to a number, but it can't convert it to a user and send a DM to that user.
Thanks in advance!
Note: I'm using slash commands, not sure if that makes any difference.
You can use:
await client.fetch_user(id2)
If this does not work, then maybe id2 is not a valid user id.
i want to create a bot, who will get user a role via reaction.
The code seems to be working but i get an error in console.
But i get an error.
Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "slh.py", line 47, in on_reaction_add
await user.add_roles(user, newrole)
File "/home/pi/.local/lib/python3.7/site-packages/discord/member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/pi/.local/lib/python3.7/site-packages/discord/http.py", line 223, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "slh.py", line 47, in on_reaction_add
await user.add_roles(user, newrole)
File "/home/pi/.local/lib/python3.7/site-packages/discord/member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/pi/.local/lib/python3.7/site-packages/discord/http.py", line 223, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
I don't know why i get this error. Because the role "testrole" is exist in my discord. I have try to use discord.utils.get withe name="channelname" and with id="723xxxxx". Both brings the same error.
The Bot has all privilegs/rights on discord.
Who can help me to fix this issue ?
Here is the code:
#bot.event
async def on_reaction_add(reaction, user):
if reaction.emoji == '✅':
newrole = discord.utils.get(user.guild.roles, name="testrole")
await user.add_roles(user, newrole)
Hope someone can help me please.
The problem is that it's trying to add user as a role. You can simply delete that, you do not need to pass it in as an argument as you are already calling the function from the class. Use this instead:
await user.add_roles(newrole)
My code is exactly
This
(With my token of course)
When I run it, my bot starts up as normal, but when a new person is added to the server, i get this.
------
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\USRNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "test.py", line 9, in on_member_join
await client.send_message(server, fmt.format(member, server))
File "C:\Users\USRNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 1152, in send_message
data = yield from self.http.send_message(channel_id, content, guild_id=guild_id, tts=tts, embed=embed)
File "C:\Users\USRNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 198, in request
raise NotFound(r, data)
discord.errors.NotFound: NOT FOUND (status code: 404): Unknown Channel
(Sorry about it not being in a code block, I'm new to stack exchange)
Any help would be appreciated. Thanks
This will not work anymore because discord removed default channels so sending it to server will not work. You should replace server with discord.Object('insert channel id') if you are using async or discord.Object(insert channel id) if you are using the rewrite branch. Note the string vs int difference. Good luck :)