Trying to send a message to a specific channel using Discord.py rewrite and it isn't working
Asked Answered
S

6

9

I'm currently working on a discord bot and I'm trying to send a message to a specific channel using Discord.py rewrite once the user levels up, and I'm getting this error:

   await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
AttributeError: 'NoneType' object has no attribute 'message'

Here is all the code:

import discord
from discord.ext import commands

import json
import asyncio

class Levels(commands.Cog):
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.bot.user:
            return

        author_id = str(message.author.id)
        bot = commands.Bot(command_prefix='!')

        if author_id not in self.users:
            self.users[author_id] = {}
            self.users[author_id]['level'] = 1
            self.users[author_id]['exp'] = 0

        self.users[author_id]['exp'] += 1

        if author_id in self.users:
            if self.lvl_up(author_id):
                channel = bot.get_channel('636399538650742795')
                await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")

    def __init__(self, bot):
        self.bot = bot

        with open(r"cogs\userdata.json", 'r') as f:
            self.users = json.load(f)

            self.bot.loop.create_task(self.save_users())

    async def save_users(self):
        await self.bot.wait_until_ready()
        while not self.bot.is_closed():
            with open(r"cogs\userdata.json", 'w') as f:
                json.dump(self.users, f, indent=4)

            await asyncio.sleep(5)


    def lvl_up(self, author_id):
        author_id = str(author_id)
        current_xp = self.users[author_id]['exp']
        current_lvl = self.users[author_id]['level']
        if current_xp >= ((3 * (current_lvl ** 2)) / .5):
            self.users[author_id]['level'] += 1
            return True
        else:
            return False

I'm really not sure what the issue is here but if anyone knows the problem I would be very appreciative if you could let me know how I can correct this.

Thanks for reading I've been trying to figure this out for hours.

Edit: Still having the issue.

Staggs answered 9/12, 2019 at 20:2 Comment(0)
B
15

You get AttributeError because channel is None.

To fix it you need to remove quotes from channel id like this:

channel = bot.get_channel(636399538650742795)

This is described here: https://discordpy.readthedocs.io/en/latest/migrating.html#snowflakes-are-int


Also i see another error on the next line. The channel has no message attribute too. I think you need to fix it like this:

await channel.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
Butz answered 10/12, 2019 at 10:16 Comment(3)
Sadly this didn't work as it returns AttributeError: 'NoneType' object has no attribute 'send' nowStaggs
It means the id 636399538650742795 is wrong. The bot doesn't have access to it, or this channel does not exists.Butz
I've recopied the channel ID a dozen times, the bot also has access to this channel because it can receive commands and send messages in the channel as wellStaggs
A
8

I was able to send messages using this guide: https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel the code I used is:

channel = client.get_channel(12324234183172)
await channel.send('hello')
Ackler answered 3/2, 2021 at 14:18 Comment(0)
D
3
@bot.command()
async def lvl_up(member: discord.Member):
    """Send a level up message"""
    channel = bot.get_channel(channel_id) # channel id should be an int

    if not channel:
        return
        
    await channel.send(f"GG {member}, u lvled up") # Whatever msg u want to put

Try using that code for the channel and sending the message, then add ur logic. I'm new to Stack Overflow so idk if I formatted that code correctly

Darius answered 26/7, 2021 at 3:49 Comment(0)
L
0

you need to put it in an async function

so instead of

channel = bot.get_channel(<channel id>)

you should do

async def get_channel():
    channel = bot.get_channel(<channel id>)

asyncio.run(get_channel())
Latish answered 17/1, 2023 at 10:50 Comment(0)
M
0

channel = discord.utils.get(ctx.guild.channels, id=xxxxxd) await channel.send("pong!")

Mckissick answered 18/9, 2023 at 3:35 Comment(2)
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Ingar
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewPraemunire
B
-1

Not sure if this is solved (sorry I'm new to stack overflow) but using this made it work

@bot.command()
async def Hello(ctx):
  channel = bot.get_channel(Insert Channel ID)
  await channel.send('Hello')

Using this I didn't get the NoneType error.

Berretta answered 9/1, 2021 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.