Discord Bot : 'Message' object has no attribute 'channell' - python

I have created a Discord bot with a Python script. This is a simple Discord bot where users can interact with it via specific messages. For example: when the user types "roll", the bot will roll the dice and give a random number.
main.py
import bot
if __name__ == '__main__':
bot.run_discord_bot()
bot.py
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.get_response(user_message) # Need to be implemented
await message.author.send(response) if is_private else await message.channell.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = ''
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now running!')
#client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
responses.py
import random
def get_response(message: str) -> str:
p_message = message.lower()
if p_message == 'hello':
return 'Hey there!'
if p_message == 'roll':
return str(random.randint(1,9))
if p_message == '!help':
return '`This is a help message that you can asked for.`'
return 'I didn\'t understand what you wrote. Try typing "!help".'
When the user input a hello, the bot did not respond and the code terminal print out an error message: 'Message' object has no attribute 'channell'
What happen? and how to fix it?

You have a typo. It should be message.channel not message.channell

Related

unknown discord.py glitch

Hello I was following a discord bot tutorial video step by step yet when i publish my code and try to respond to it, it would completly ignore me and I have no idea why it does this here is the whole code.
import discord
import random
TOKEN = 'is here'
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'bot':
if user_message.lower() == 'hello':
await message.channel.send(f'hello {username}!')
elif user_message.lower() == 'bye':
await message.channel.send(f'see you later {username}!')
return
elif user_message.lower() == '!random':
response = f'this is your random number: {random.randrange(50000)}'
await message.channel.send(response)
return
if user_message.lower() == '!anywhere':
await message.channel.send('this can be used anywhere!')
return
client.run(TOKEN)
Fixed it for you. Your client.run(token) was inside the last if statement so your bot would not have even started also you need to enable intents in your developer account otherwise the bot might not be able to read messages.
username = str(message.author).split('#')[0] is unnecessary when you can just use username = message.author.name
import discord
import random
import asyncio
intents = discord.Intents.default()
intents.messages = True
intents.guild_messages = True
intents.message_content = True
client = discord.Bot(intents=intents, messages = True, guild_messages = True, message_content = True)
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
username = message.author.name
channel = str(message.channel.name)
if message.author == client.user:
return
if message.channel.name == 'bot':
if message.content.startswith('hello'):
await message.channel.send(f'hello {username}!')
if message.content.startswith('!anywhere'):
await message.channel.send('this can be used anywhere!')
return
client.run('token_here')

Getting error on discord bot discord.py for typing in role

I get this error on my bot when mentioning a role,here is the error,
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unhashable type: 'set'
my code:
import os
import discord
from discord.ext import commands
from discord import Intents
from apikeys import *
intents = Intents.all()
client = commands.Bot(intents = intents, command_prefix="-", case_insensitive=True)
#client.event
async def on_ready():
for emoji in client.emojis:
print("Name:", emoji.name + ",", "ID:", emoji.id)
print('Bot is Online {0.user}'.format(client))
print("--------------------------------------------------------------------------------------------------------------------------------------------------------")
client.remove_command('help')
emojigood = '\N{THUMBS UP SIGN}'
emojibad="\N{THUMBS DOWN SIGN}"
#client.command()
async def war(ctx):
await client.wait_until_ready()
embed = discord.Embed(title='War', description='You are starting a war, do you want to continue?', color=0x00000)
msg = await ctx.send(embed=embed)
await msg.add_reaction(emojigood)
await msg.add_reaction(emojibad)
def check(r, user):
return (r.emoji == emojigood or r.emoji == emojibad) and r.message == msg and user != client.user
r, user = await client.wait_for('reaction_add',check=check)
if r.emoji == emojigood:
embed = discord.Embed(title='War', description='Please now choose a country', color=0x00000)
await ctx.send(embed=embed)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await client.wait_for('message', check=check)
if len(msg.role_mentions) > 0:
role = msg.role_mentions[0]
channel = client.get_channel({849549009038344262})
await channel.send(f"{role.mention} {ctx.author} has declared war on you.")
else:
await ctx.send("Invalid role mentioned")
else:
await ctx.send("Cancelled")
client.run(token)
What's meant to happen:
Me:-war
Bot:Are you sure
Me:reacts
Bot:Type in role
Me:(role name)
Bot:....
{849549009038344262}
is a set literal for a set containing a number. discord.py is using hashing under the hood to look up channels, which is failing because it is not possible to hash sets. You should be passing a regular int instead of a set:
channel = client.get_channel(849549009038344262)

Getting message content with Discord.py

I would like to have a command like $status idle and it would do the follow
variblething = 'I am idle'
activity = discord.Game(name=variblething)
await client.change_presence(status=discord.Status.idle, activity=activity)
then they can do $message write what you want the status to be
then it would change what the activity message is. I hope this all makes sense. My current code is the following
import discord
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('$helloThere'):
await message.channel.send('General Kenobi')
Firstly I would highly advise that you use prefixes and the command decorators/functions.
This means that your on_message() function won't be a mile long. To set your bot's command prefix, you can do:
from discord.ext import commands
bot = commands.Bot(command_prefix ='$')
This will allow you to make commands like so:
#bot.command()
async def changeStatus(ctx, *, status):
if status == 'online':
new_status = discord.Status.online
elif status == 'offline':
new_status = discord.Status.offline
elif status == 'idle':
new_status = discord.Status.idle
elif status == 'dnd':
new_status = discord.Status.dnd
else:
return
await bot.change_presence(status=new_status, activity=discord.Game(f'I am {status}'))

Discord Py can't figure out how to add roles

I've looked everywhere and people just tell me to use the documentation and that doesn't help, I've already got on_message(message) defined so I can't use a member parameter and I want people to be set to a certain role when they say a keyword
here's what I got but it doesn't work:
if message.content.lower() == "!changeadmin"
role = discord.utils.get(server.roles, name="Administrator")
await client.add_roles(member, role)
I always get returned with
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\josep\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\josep\OneDrive\Documents\New folder\New folder\mybot1.py",
line 58, in on_message
role = discord.utils.get(server.roles, name="admin")
AttributeError: 'str' object has no attribute 'roles'
EDIT:
This is my full code (excluding the token at the bottom):
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
import ctx
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
chat_filter = ["CUNT", "NIGGER", "NIGGA", "FUCK", "BITCH", "DICK", "WANKER"]
bypass_list = ["227007454775476224"]
possible_responses = [
'That is a resounding no',
'It is not looking likely',
'Too hard to tell',
'It is quit possible',
'Definitely',
]
server = '242547220765868033'
roles = ['442351132615114772']
#client.event
async def on_ready():
print("Bot is online and connected to Discord")
bot = commands.Bot(command_prefix='!', description='A bot that greets the user back.')
#client.event
async def on_message(message):
contents = message.content.split(" ") #contents is a list type
for word in contents:
if word.upper() in chat_filter:
if not message.author.id in bypass_list:
try:
await client.delete_message(message)
await client.send_message(channel.message, "**Hey!** You're not allowed to use that word here!")
except discord.errors.NotFound:
return
if message.content.upper().startswith('!PING'):
userID = message.author.id
await client.send_message((discord.Object(id='442333293539622913')), "<#%s> Pong!" % (userID))
if message.content.upper().startswith('!SAY'):
if message.author.id == "227007454775476224" or message.author.id == "399959323591180288":
args = message.content.split(" ")
await client.send_message(message.channel, "%s" % (" ".join(args[1:])))
else:
await client.send_message(message.channel, "Sorry only the bot owner has permission to use this command")
if message.content.lower() == "cookie":
await client.send_message(message.channel, ":cookie:") #responds with Cookie emoji when someone says "cookie"
if message.content.lower() == "!website":
await client.send_message(message.channel, "habbo.com")
if message.content.upper().startswith('!EIGHTBALL'):
await client.send_message(message.channel, random.choice(possible_responses))
if message.content.lower() == '!changeadmin':
role = discord.utils.get(server.roles, name="admin")
await client.add_roles(member, role)
sorry if this a late reply :)
so if u wanna add roles to members try this code:
#client.command()
#commands.has_permissions(administrator=True)
async def giverole(ctx,member :discord.Member,role):
try:
add_role= discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(add_role)
await ctx.send('Updated')
except:
await ctx.send("role not found!")
so the code gonna work like this: let's say prefix= "?"
?giverole #member example
the bot gonna search a role name "example" from guild role and give it to #member

Discord bot not recognizing commands

I'm new to the discord API and I'm having trouble figuring out why my commands are not recognized. I've read through the documentation, but I'm not exactly sure where to look. Any help would be appreciated. Don't mind the hard-coded lists. I plan on changing that in the future. For now I just want to make sure that it works.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot online!")
#client.command(pass_context=True)
async def add_roles(member, *roles):
if message.content.startswith("!role"):
role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"]
entered_role = message.content[6:].upper()
role = discord.utils.get(message.server.roles, name=entered_role)
if role is None or role.name not in role_list:
# If the role wasn't found by discord.utils.get() or is a role that we don't want to add:
await client.send_message(message.channel, "Role doesn't exist.")
return
elif role in message.author.roles:
# If they already have the role
await client.send_message(message.channel, "You already have this role.")
else:
try:
await client.add_roles(message.author, role)
await client.send_message(message.channel, "Successfully added role {0}".format(role.name))
except discord.Forbidden:
await client.send_message(message.channel, "I don't have perms to add roles.")
#client.command(pass_context=True)
async def remove_roles(member, *roles):
if message.content.startswith("!unassign"):
role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"]
roles_cleared = True
for r in role_list:
# Check every role
role = discord.utils.get(message.server.roles, name=r)
if role in message.author.roles:
# If they have the role, get rid of it
try:
await client.remove_roles(message.author, role)
except discord.Forbbiden:
await client.send_message(message.channel, "I don't have perms to remove roles.")
roles_cleared = False
break
if roles_cleared:
await client.send_message(message.channel, "Roles successfully cleared.")
client.run("mytoken")
In function you need to have ctx variable
#client.comman(pass_context = True)
async def some_command(ctx, bla_bla, and_bla_bla):
pass
i think...
tell if it was helpful for u

Categories

Resources