unknown discord.py glitch - python

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')

Related

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

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

Why is my bot.command function not working?

So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ? Also seems like i need to post more details, don't pay attention to this : Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.

It say TypeError: object bool can't be used in 'await' expression

import os
import discord
client = discord.Client()
#client.event
async def on_ready():
print("Logged in as {0.user}".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "Hi":
await message.channel.send("Hi")
elif message.content == "Hello":
await message.channel.send("Hello")
elif await message.content.endswith("birthday"):
await message.channel.send("Happy birthday")
token = os.environ['TOKENS']
client.run(token)
You accidentally awaited the condition in the third elif which is actually not an coroutine. This be able should fix it :
import os
import discord
client = discord.Client()
#client.event
async def on_ready():
print("Logged in as {0.user}".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "Hi":
await message.channel.send("Hi")
elif message.content == "Hello":
await message.channel.send("Hello")
elif message.content.endswith("birthday"):
await message.channel.send("Happy birthday")
token = os.environ['TOKENS']
client.run(token)

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)

Cannot Check Reaction In Discord.py

So basically i was making a modmail system and the problem was we wanted the person who dmed the bot has to react to ✅ if he reacts then the bot has to reply him "OK"
but the code was not working so what is the problem how to fix it?
import discord
import asyncio
client = discord.Client()
#client.event
async def on_message(message):
# empty_array = []
# modmail_channel = discord.utils.get(client.get_all_channels(), name="mod-mail")
if message.author == client.user:
return
if str(message.channel.type) == "private":
embed = discord.Embed(title='Confirmation',
color=0x03d692)
embed.add_field(name="You're sending this message to **The Dynamic Legends**", value="React with :white_check_mark: to confirm." + "\nTo cancel this request, react with :x:.", inline=False)
confirmation_msg = await message.author.send(embed=embed)
await confirmation_msg.add_reaction('✅')
await confirmation_msg.add_reaction('❌')
sent_users = []
sent_users.append(message.author.name)
try:
print('Working')
def check1(reaction, user):
return user == client.user and user!='Mod Mail Humara#5439' and str(reaction.emoji) == '✅'
reaction, user = await client.wait_for("reaction_add", timeout=30.0, check=check1)
# print(reaction, user)
if str(reaction.emoji) == '✅':
message.author.send('yes)
client.run('TOKEN')
There's a logic problem in the check func
return user == client.user
It simply doesn't make sense, instead of == use != and don't put the user!='Mod Mail Humara#5439' part
Your check func fixed:
def check1(reaction, user):
return user != client.user and str(reaction.emoji) == '✅'
Also message.author.send is a coroutine, so you need to await it
await message.author.send("whatever")
Your code:
#client.event
async def on_message(message):
if message.author == client.user:
return
if isinstance(message.channel, discord.DMChannel):
embed = discord.Embed(title='Confirmation', color=0x03d692)
embed.add_field(name="You're sending this message to **The Dynamic Legends**", value="React with :white_check_mark: to confirm." + "\nTo cancel this request, react with :x:.", inline=False)
confirmation_msg = await message.author.send(embed=embed)
await confirmation_msg.add_reaction('✅')
await confirmation_msg.add_reaction('❌')
sent_users = []
sent_users.append(message.author.name)
try:
def check1(reaction, user):
return user != client.user and str(reaction.emoji) == '✅'
reaction, user = await client.wait_for("reaction_add", timeout=30.0, check=check1)
if str(reaction.emoji) == '✅':
await message.author.send('yes')
except Exception as e:
pass

Categories

Resources