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.
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)
So I am using Python 3 to create a script with Telegram API but have come across a pickle.
Essentially I want anything I post to one channel to automatically be posted to a list of other channels.
As there are a lot of channels I am pretty sure I have split it over multiple lines, keeping the variables aligned with the first delimiter as per PEP8 code layout advice. However, for some reason, the code only posts content to the first line of channels in the list and not the others.
Right now my code is:
from telethon import TelegramClient, events
api_id = 9969279 #API_ID
api_hash = 'd5fa4ca47bcdb6f5bda7271f30e607e9' #API_HASH
channel = [-1001612029593] #MAIN_CHANNEL_ID
to_channel = [-1001408569373,-1001450011693,-1001589562089,-1001324581893,-1001486742214,-1001262799053,-1001577547504,-1001751417089,
-1001714682472,-1001173439993,-1001564319953,-1001458872203,-1001580609047,-1001454607304,-1001412291633,-1001307551599,
-1001472656059,-1001577461465,-1001577461465,-1001438912928,-1001166100393,-1001226585647,-1001662052611,-1001412291633,
-1001213093519,-1001543013350,-1001599148038,-1001250770087,-1001489822613,-1001586463068,-1001173726857,-1001425575134,
-1001549263406,-1001566043627,-1001605175905,-1001229590696,-1001442156928] #OTHER_CHANNELS
client = TelegramClient('TGBot', api_id, api_hash)
#client.on(events.NewMessage(chats=channel))
async def my_event_handler(event):
if event.message:
for channelx in to_channel:
await client.send_message(channelx, event.message)
client.start()
client.run_until_disconnected()
I'm wondering as to whether the lines are too long - other than that I can't think of why it won't post all channels?
EDIT: When running the script I get the following notes on my CMD
Traceback (most recent call last):
File "C:\Users\mimif\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py", line 451, in _dispatch_update
await callback(event)
File "C:\Users\mimif\OneDrive\Desktop\python\main.py", line 18, in my_event_handler
await client.send_message(channelx, event.message)
File "C:\Users\mimif\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\messages.py", line 825, in send_message
return await self.send_file(
File "C:\Users\mimif\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\uploads.py", line 412, in send_file
return self._get_response_message(request, await self(request), entity)
File "C:\Users\mimif\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "C:\Users\mimif\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 84, in _call
result = await future
telethon.errors.rpcerrorlist.ChannelPrivateError: The channel specified is private and you lack permission to access it. Another reason may be that you were banned from it (caused by SendMediaRequest)```
I have an id from a group chat, but when I try to send a message there, I get this error:
Traceback (most recent call last):
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
return await asyncio.gather(*tasks)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
return await self.message_handlers.notify(update.message)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "D:\github\repositories\python-bot\bot5.py", line 77, in cmd_create_dem
await bot.send_poll(chat_id=id,
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\bot.py", line 1532, in send_poll
result = await self.request(api.Methods.SEND_POLL, payload)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.ChatNotFound: Chat not found
If I try to send to any other group, then everything works. Why is that?
code:
#dp.message_handler(commands=['opros'])
async def prikol(message: types.Message):
id = {-numbers}
await bot.send_message(id, 'ok')
i changed my id to {numbers}
My id has 14 characters including the minus, while the rest of the groups have like 10 characters. Could this affect something?
If you get id without -100 (example: 1234561) you need add "-100" to this id to use it with bot (ex: -1001234561)
I have two suggestions:
Be sure that your bot must be an admin of this group to be able to send messages.
Double check group id.
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 :)
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.