Discord.py int has no attribute send - python

Hey so I got this code
import discord
import asyncio
import random
import os
import time
from discord.ext import tasks, commands
client = discord.Client()
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format (client))
async def background_loop():
await client.wait_until_ready()
while not client.is_closed():
channel =(814588208091365426)
messages = ["Test1", "Test2", "Test3"]
await channel.send(random.choice(messages))
await asyncio.sleep(60)
client.loop.create_task(background_loop())
client.run(os.getenv('token'))
and I am getting this error:
future: <Task finished name='Task-1' coro=<background_loop() done, defined at main.py:15> exception=AttributeError("'int' object has no attribute 'send'")>
Traceback (most recent call last):
File "main.py", line 20, in background_loop
await channel.send(random.choice(messages))
AttributeError: 'int' object has no attribute 'send'
I also tried adding
return messages
I didnt get an error but the bot also didnt do anything.
Thanks in advance

You are trying to call the function send on the number 814588208091365426, this is the channel id, you need to convert the channel id to a channel with:
channel = client.get_channel(814588208091365426)

Related

AttributeError: 'NoneType' object has no attribute 'send' when sending message

so I checked all over in stack overflow for answers and nothing.
Im trying to make it that when the bot fires up it will send a message in a channel, I have alr checked if the bot can see and talk in the channel and they can.
My code:
import discord
from discord.ext import commands
from datetime import datetime
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="!", intents=intents, case_insensitive=True)
client = discord.Client(intents=intents)
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
current_time = datetime.now().strftime("%H:%M:%S")
channel = bot.get_channel('1069075658979954700')
embed = discord.Embed(title="GAH Verification",
description="I have awoken",
color=discord.Color.green())
embed.set_footer(text=current_time)
await channel.send('Hi')
bot.run(
"MTA2OTI2NDQ0MTQwMjcyODU3MQ.GV353u.XXagXFsp3Ax4vRxvt3y5s6P9FPPDrOeMh2M7jI")
Error:
Traceback (most recent call last):
File "/home/runner/GAH-Bot/venv/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 19, in on_ready
await channel.send('Hi')
AttributeError: 'NoneType' object has no attribute 'send'
currently bot.get_channel() returns None,
either because it dont get it because 1069075658979954700 is in quotes
you should try using:
bot.get_channel(1069075658979954700)
and check if the bot has access to the channel
if this won't work you can always try to get the channel via the server this should work 100% because maybe the channel is not loaded to the cache directly idk
server = bot.get_guild(1234) # server id here
channel = await server.fetch_channel(12345) # channel id here

Trying to send a message to a specific channel from a different file , discord.py

i splitted some code into another file and i get "'NoneType' object has no attribute 'send'"
as i read , its should be a error like "the channel dont exist" "the bot dont have permission"
but tahts wrong , i can send messages just fine from the main.py in the specific channel just not from the loging.py . here my code .
#bot.py
import discord
import asyncio
from discord.ext import commands
import os
from dotenv import load_dotenv
from datetime import datetime, timedelta, date, time, timezone
import time
import loging
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
bot = commands.Bot(command_prefix=commands.when_mentioned_or("$"), help_command=None)
#bot.command(name='test', help='this command will test')
async def test(ctx):
await loging.comlog(ctx)
bot.run(TOKEN)
#loging.py
import discord
import asyncio
from discord.ext import commands
import os
from datetime import datetime, timedelta, date, time, timezone
import time
bot = commands.Bot(command_prefix=commands.when_mentioned_or("$"), help_command=None)
timestamp = datetime.now()
timenow = str(timestamp.strftime(r"%x, %X"))
async def comlog(ctx):
channel = ctx.channel
channelid = ctx.channel.id
username = ctx.author
usernameid = ctx.author.id
logingchan = await bot.fetch_channel(983811124929630239)
em = discord.Embed(title=f'${ctx.command}', description=f'{timenow}', color=0x00FF00)
em.set_thumbnail(url=username.avatar_url)
em.add_field(name="Channel:", value=f'{ctx.channel.mention} \n{channelid}', inline=True)
em.add_field(name="User:", value=f'{username}\n{usernameid}', inline=True)
print(f'{timenow}: $help: in "{channel}" by "{username}"')
await logingchan.send(embed=em)
await ctx.message.delete()
for testing i replaced the cahnnel with "ctx" and this works just fine
Ignoring exception in command test:
Traceback (most recent call last):
File "C:\Users\Asuka\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Asuka\Desktop\PROJECT\Discord_Bot\bot.py", line 149, in test
await loging.comlog(ctx)
File "C:\Users\Asuka\Desktop\PROJECT\Discord_Bot\loging.py", line 23, in comlog
await logingchan.send(embed=em)
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Asuka\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Asuka\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Asuka\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: 'NoneType' object has no attribute 'send'
yea i know ppl say now , the cahnnel dont exist , the bot dont have premmision . false , why can i send in the exact same channel with my main.py but not with the loging.py . also , if i dont send in a specific channel , and send the embed in channel where the command got used , and i use the channel with the id , my bot can reply in the exact same channel.
You have two separate bots in your two modules.
In the bot.py, you make a bot that you later run with the run method. This bot is fine, and it's connected to discord and can do a bunch of things.
However, you made a second bot in logging.py. This bot isn't actually doing anything and it was never started, so any attempts to get or fetch anything from discord will fail. What you need to do is to give the bot instance to the other module.
You can do this by either putting it into a class, or passing the bot as an argument, which I will show here:
async def comlog(bot, ctx):
channel = ctx.channel
channelid = ctx.channel.id
username = ctx.author
usernameid = ctx.author.id
logingchan = await bot.fetch_channel(983811124929630239)
em = discord.Embed(title=f'${ctx.command}', description=f'{timenow}', color=0x00FF00)
em.set_thumbnail(url=username.avatar_url)
em.add_field(name="Channel:", value=f'{ctx.channel.mention} \n{channelid}', inline=True)
em.add_field(name="User:", value=f'{username}\n{usernameid}', inline=True)
print(f'{timenow}: $help: in "{channel}" by "{username}"')
await logingchan.send(embed=em)
await ctx.message.delete()
# Then pass in the bot when you call the function
#bot.command(name='test', help='this command will test')
async def test(ctx):
await loging.comlog(bot, ctx)
Then you can just delete your second bot definition in logging.py.
If you want permission failure messages you need to use try/except:
try:
await logingchan.send(embed=em)
except discord.errors.Forbidden:
# don't have permissions, do something here
There isn't a bot variable in loging.py
If you want to split bot commands you should make cogs instead
Cogs are like command groups
This is how you do it:
# main.py
from discord.ext import commands
from loging import my_commands_cog
bot = commands.Bot(command_prefix = "idk!")
bot.add_cog(my_commands_cog)
# loging.py
from discord.ext import commands
class my_commands_cog(commands.Cog)
#commands.command(name = "idk")
async def idk(ctx, * , arg):
# stuff
print("idk")
Check it out here: Cogs

Discord.py Errors

Today I wanted to try to create a discord bot with python. The problem i have is, that there is always an error message when I start the program:
Traceback (most recent call last):
File "D:\...\Discord Bot\PythonGPU_Bot\bot.py", line 1, in <module>
import discord
File "C:\Users\...\Python\Python39\lib\discord\__init__.py", line 4, in <module>
client = discord.Client()
AttributeError: partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import)
Thats the Error message I always get.
This is my script:
import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print('Logged in as {}'.format(client.user.name))
client.loop.create_task(status_task())
async def status_task():
while True:
await client.change_presence(activity=discord.Game('Hello <:'))
await asyncio.sleep(1)
await client.change_presence(activity=discord.Game('Hello c:'))
await asyncio.sleep(1)
#client.event
async def on_message(message):
if message.auther.bot:
return
if '.status' in message.content:
await message.channel.send('SSSS')
client.run('ID')
I hope someone can help me out.
The name of your file is discord.py, rename the file
rename it to bot.py or main.py or anything you like and your issue will be fixed
Why does it happen?
Since your file name is discord.py, it is actually importing that file and not the actual discord.py module you installed with pip.

AttributeError: 'NoneType' object has no attribute 'send' discord.py

I'm trying to send a dm to a specific user with the command .dmtest, but whenever I run the command I get the error mentioned in the title
Here is my code:
import discord
from discord.ext import commands
import os
import requests
import asyncio
from keep_alive import keep_alive
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.dmtest'):
user = client.get_user(384185404510961664)
# await message.author.send(...)
await message.channel.send('test worked')
await user.send('a')
keep_alive()
client.run(os.getenv('TOKEN'))
Error:
line 78, in on_message
await user.send('a')
AttributeError: 'NoneType' object has no attribute 'send'
After playing around with your code a bit, I found that I got DMed "a" after replacing await user.send('a') with await message.author.send('a'). After making that change, the line user = client.get_user(384185404510961664) is unnecessary, and can be deleted.
EDIT: Since this isn't what you're looking for, I dug around the internet and found that you just needed to replace client.get_user(id) with await client.fetch_user(id).

AttributeError: 'list' object has no attribute 'channel' discord.py

I am trying to create a function that would clear the chat on discord using https://www.youtube.com/watch?v=ZBVaH6nToyM , however I think that I've declared channel (channel = ctx.message.channel) however entering .clear would result in an error
Ignoring exception in command clear
Traceback (most recent call last):
File "C:\Users\mark\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\discord\ext\commands\core.py", line 50, in
wrapped
ret = yield from coro(*args, **kwargs)
File "C:/Users/mark/Desktop/purge.py", line 17, in clear
await client.delete_message(messages)
File "C:\Users\mark\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\discord\client.py", line 1261, in delete_message
channel = message.channel
AttributeError: 'list' object has no attribute 'channel
import discord
from discord.ext import commands
from discord.ext.commands import Bot
TOKEN = "token here"
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print("Bot is online")
#client.command(pass_context = True)
async def clear(ctx, amount=100):
channel = ctx.message.channel
messages = []
async for message in client.logs_from(channel,limit=int(amount)):
messages.append(messages)
await client.delete_message(messages)
await client.say('message has been deleted')
client.run(TOKEN)
You are basically appending a list itself over and over again
my_list=[]
my_list.append(my_list)
print(my_list)
Which results in something like this
>>[[[...]]
The command should be something like this
#bot.command(pass_context=True)
async def clear(msg,amt:int=20): #can be converted into int via :type
messages=[]
async for i in bot.logs_from(msg.message.channel,limit=amt):
messages.append(i)
await bot.delete_messages(messages)
Also a heads up note, you can't bulk delete messages that are older than 14 days I think meaning that you can't use the delete_messages and only delete it individually

Categories