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.
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 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
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 have created a telegram bot. where I am asking the users to send the location.
import aioschedule as schedule
import asyncio
from asyncio import futures
#bot.on(events.CallbackQuery(pattern=r'sendloc'))
async def sendlocation(event):
sender = await event.get_input_sender()
my_user = await bot.get_entity(sender.user_id)
userId = my_user.id
async with bot.conversation(userId) as conv:
await conv.send_message('receiving', buttons=[Button.request_location(text='send Location', resize=10)])
try:
response = await conv.get_response()
except futures.TimeoutError as e:
await conv.cancel_all()
return
conv.send_message('location accepted')
async def methodToSendLocation():
users = pd.read_csv('telegramId.csv')
for user in users['Telegram ID']:
try:
await bot.send_message(user, 'send location', buttons=Button.inline('sendloc'))
except ValueError as e:
print('Error occurred for user: {telId}'.format(telId=user))
def main():
'''start the bot'''
bot.start()
schedule.every().day.at("11:00").do(methodToSendLocation)
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(schedule.run_pending())
bot.run_until_disconnected()
if __name__ == '__main__':
main()
what does my program do?
It will run every day at 11:00 AM.
It will fetch the telegram Id from the CSV file and send a message to the users to send the location and we process the location.
My Query:
Sometimes there occurs a timeout error in sendlocation method of my program and recently I observed that for some users timeout error occurred within a minute after the user clicks the send Location button.
I am not able to understand why the error occurred in a very short interval.
And sometimes there has been a delay to send the location to the bot after the user clicks the send Location button.
stack trace:
Traceback (most recent call last):
File "app.py", line 118, in sendlocation
response = await conv.get_response()
File "C:\Users\Swarnim\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 449, in wait_for
raise futures.TimeoutError()
concurrent.futures._base.TimeoutError
Stack (most recent call last):
File "app.py", line 450, in <module>
main()
File "app.py", line 444, in main
loop.run_until_complete(schedule.run_pending())
File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete
self.run_forever()
File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever
self._run_once()
File "/usr/lib/python3.6/asyncio/base_events.py", line 1451, in _run_once
handle._run()
File "/usr/lib/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "/home/epluser/.venv/automation/lib/python3.6/site-packages/telethon/client/updates.py", line 443, in _dispatch_update
await callback(event)
File "app.py", line 121, in sendlocation
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.