I'm making a bot with Discord.py and I've some question how to use the function create_custom_emojis() because whatever I do, I keep getting the HTTP Error 400.
Here's my code to create the emoji:
with open("data/emojis/image.png", "rb") as image:
image_byte = image.read()
emoji = await self.bot.create_custom_emoji(server, name="emo", image=image_byte)
And the error I get:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python35\lib\asyncio\tasks.py", line 239, in _step
result = coro.send(None)
File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 385, in read_feeds
message = await self._feed_check(server, chan_id, name, infos)
File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 198, in _feed_check
await self.create_custom_emojis(server)
File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 189, in create_custom_emojis
emoji = await self.bot.create_custom_emoji(server, name=name, image=image_byte)
File "lib\discord\client.py", line 2519, in create_custom_emoji
data = yield from self.http.create_custom_emoji(server.id, name, img)
File "lib\discord\http.py", line 202, in request
raise HTTPException(r, data)
discord.errors.HTTPException: BAD REQUEST (status code: 400)
image_byte = image.read()
Do not attempt to read from image. It is already a byte like object. Simply send this as the image.
emoji = await self.bot.create_custom_emoji(server, name="emo", image=image)
I'm not entirely sure of the exact code, but you could use the get_all_emojis() function - read about it in the Discord API.
Related
Im trying to send an embed with a thumbnail attachment to a different specific channel.
Sending on the local channel with interactions or DMs works but not to a specific channel
import discord
from interactions import Attachment, User
from discord.ui import Select, View, Button
from discord.utils import get
thumbnailFile = "attachment://thumbnail-placeholder.png"
localThumbnail = discord.File("./Source/Images/thumbnail-placeholder.png")
embedConfirm.set_thumbnail(url=thumbnailFile)
await bot.get_channel(int(ADMINREPORTCHANNEL)).send(embed=embedConfirm, view=view, file=localThumbnail)
Any idea if i am doing something wrong?
I get this output when its trying to send the embed.
Ignoring exception in view <View timeout=None children=3> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Create report' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "C:\Users\ogunt\Desktop\Discord Bot\BusBot\main.py", line 342, in button_create
await bot.get_channel(int(ADMINREPORTCHANNEL)).send(embed=embedConfirm, view=view, file=localThumbnail)
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\discord\abc.py", line 1481, in send
data = await state.http.send_files(
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\discord\http.py", line 284, in request
async with self.__session.request(method, url, **kwargs) as response:
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
self._resp = await self._coro
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\client.py", line 507, in _request
req = self._request_class(
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\client_reqrep.py", line 313, in __init__
self.update_body_from_data(data)
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\client_reqrep.py", line 507, in update_body_from_data
body = body()
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\formdata.py", line 170, in __call__
return self._gen_form_data()
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\formdata.py", line 163, in _gen_form_data
self._writer.append_payload(part)
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\multipart.py", line 831, in append_payload
size = payload.size
File "C:\Users\ogunt\anaconda3\envs\discord\lib\site-packages\aiohttp\payload.py", line 379, in size
return os.fstat(self._value.fileno()).st_size - self._value.tell()
ValueError: I/O operation on closed file
Apparently you can only send a thumbnail once then the file closes. So I created second variable to send to a different channel.
like this:
localThumbnail = discord.File("./Source/Images/thumbnail-placeholder.png")
localThumbnail2 = discord.File("./Source/Images/thumbnail-placeholder.png")
My thumbnail works now.
You need to pass file instead of url. Your using a local file, not a image URL.
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.
i have a bot which parses some links given by user. When clients want to parse realy huge amount of links, bot parses them, creates csv file from those links, sends it to user(user can download and view this file) and then raise TimeoutError
Cause exception while getting updates.
Traceback (most recent call last):
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 381, in start_polling
updates = await self.bot.get_updates(
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/bot/bot.py", line 110, in get_updates
result = await self.request(api.Methods.GET_UPDATES, payload)
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/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 "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/bot/api.py", line 139, in make_request
async with session.post(url, data=req, **kwargs) as response:
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/client.py", line 1138, in __aenter__
self._resp = await self._coro
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/client.py", line 559, in _request
await resp.start(conn)
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 913, in start
self._continue = None
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/helpers.py", line 721, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
Some example how my bot looks like(that's not real code, that's EXAMPLE):
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
def parse_1000_links():
#it takes about 10 mins and therefore that's the same like sleep(600)
sleep(600)
#dp.message_handler()
async def msg_handler(message: types.Message):
if msg == 'parse 1000 links':
res = parse_1000_links()
create_csv_from_res(res)
file_open_obj = open('data.csv', 'rb')
await bot.send_document(message.from_user.id, file_open_obj)
.....
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
User can even get from bot this final file, but after sending this file to user, bot raises this error. That's strange. If user get message, it means that everything is fine(That's my opinion)
How to fix my issue?
Thanks
You should avoid using blocking operations, cause they freeze ALL event loop.
If you can't use async version of your dependency, use executor:
https://docs.python.org/3/library/asyncio-eventloop.html#executing-code-in-thread-or-process-pools
Hi i keep getting the error message
discord.errors.LoginFailure: Improper token has been passed.
this is my code
import discord
import os
client = discord.Client()
token = os.environ['token']
async def on_ready():
await client.change_presence(game=discord.Game(name=" dm for support ;)"))
client.run("token")
this is the full error message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 293, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 247, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 11, in <module>
client.run("token")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 718, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 697, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 660, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 509, in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 297, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
and finally this is a screen shot of the token
image of token in replit secrets
any help??
Two things that I think are the cause:
In this part of the code
token = os.environ['token']
You are retrieving an environment variable, called 'token', that you should set before running your program. In case you haven't, that's easy to do:
Windows:
SET token=<value of token>
Linux based OS:
export token=<value of token>
In this way, you make sure this environment variable is set.
Second problem:
In this part of your code
client.run("token")
You are not using this variable that you previously extracted with token = os.environ['token'] , instead you are literally using the string token as your token, which I imagine is not really your token. This could be fixed, like this:
client.run(token)
Note that in this case, I'm using the variable token previously declared, instead of the string "token".
Also, this question could be helpful.
I was working on a discord bot that needed to send a file. The only change I can think of from previous file-sending situations that worked for me was that the encoding of the file was ISO-8859-1 instead of utf-8. I made the TextIO object with with open(filepath,'r',encoding='ISO-8859-1') as mp3, then under that, I used await channel.send(file=discord.File(mp3))(on later testing, even if I move the discord.File call to another line, the error is in the send method). The send line of code thew a huge chain of errors, ending with RuntimeError: Form data has been processed already. What does this error mean in my context, and what do I do to fix it? Thanks in advance!
For reference, here's the full exception chain:
await coro(*args, **kwargs)
File "/Users/nathanwolf/Documents/coding/PycharmProjects/lyrics bot/main.py", line 75, in on_message
await message.channel.send(file=discord.File(mp3))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/abc.py", line 915, in send
data = await state.http.send_files(channel.id, files=[file], allowed_mentions=allowed_mentions,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 185, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client.py", line 492, in _request
req = self._request_class(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 313, in __init__
self.update_body_from_data(data)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 507, in update_body_from_data
body = body()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/formdata.py", line 168, in __call__
return self._gen_form_data()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/formdata.py", line 132, in _gen_form_data
raise RuntimeError("Form data has been processed already")
RuntimeError: Form data has been processed already```
I fixed it, but it isn't entirely clear how I did it. Updating discord.py worked, but then the error came back once I tried to change the encoding on the mp3 file to utf-8 so discord could read it. I got around it by not giving a TextIO object to the discord.File() method and instead gave it the name of the file. Somehow that worked.