Im trying to make a bot that can create roles but the bot is not recognizing my command.
I have tried using OpenAI but its knowledge is limited. I just need a working way to receive commands and create the roles. This is one of the biggest
import sys
command_prefix = "!"
async def create_role(guild, role_name):
# Create the role
role = await guild.create_role(name=role_name)
return role
#client.event
async def on_message(message):
if message.content.startswith(f"{command_prefix}gr"):
# Split the message into a list of arguments
args = message.content.split(" ")
# The name of the role is the second argument
role_name = args[1]
print(f"Creating role {role_name}") # Debug statement
# Create the role
role = await create_role(message.guild, role_name)
# Give the role to the user who sent the message
await assign_role(message.author, role)
await message.channel.send(
f'Created role {role_name} and gave it to {message.author}')
client.run(
'TOKEN')
You should use commands
from discord.ext import commands
bot = commands.Bot(command_prefix = '!') # prefix
#bot.command(name = "gr") # gr would be an example command, !gr <something>
async def do_on_command_function(ctx, msg):
# msg will store the message after the command
await ctx.send(arg)
Related
Im trying to make a verify command where it sends me a dm, and I can check wether they are verified or not, here is my code:
import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import time
import json
token = os.environ['token']
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix=get_prefix)
#client.event
async def on_ready():
print('Bot is ready')
await client.change_presence(activity=discord.Game(f'My prefix is {get_prefix}'))
#client.command()
async def verify(ctx, message, jj=discord.Member.get_user("270397954773352469")):
person = message.author
jj.create_dm()
await ctx.send('Awaiting Verification, you will recieve a dm when you are verified')
await jj.send(f'{person} is trying to be verified, do you know him/her?')
You don't have to use parameter message use ctx which you already have to get ctx.author. You can get a user by id only with client.get_user or client.fetch_user (and use it inside a function, not as a parameter). Last thing - you usually don't have to use create_dm(), but if you want to you can, but remember to correct it to await jj.create_dm().
#client.command()
async def verify(ctx):
jj = await client.fetch_user(270397954773352469)
person = ctx.author
await ctx.send('Awaiting Verification, you will recieve a dm when you are verified.')
await jj.send(f'{person.mention} is trying to be verified, do you know him/her?')
If you have something like verified role (you won't get a message if someone is verified):
#client.command()
async def verify(ctx):
role = discord.utils.get(ctx.guild.roles, name="verified") # name of your role
person = ctx.author
if role in person.roles:
await ctx.send('You are already verified!')
else:
jj = await client.fetch_user(270397954773352469)
await ctx.send('Awaiting Verification, you will recieve a dm when you are verified.')
await jj.send(f'{person.mention} is trying to be verified, do you know him/her?')
I was wondering how I can set a role for a member, after he reacted to an emoji.
I've tried several ways but it hasn't worked anything yet.
AttributeError: 'Guild' object has no attribute 'add_roles'
I always get this error, I tried to replace Guild with User, Payload or Member, but it doesn't find it anyway
I have two file in my 'cogs' folder:
• roles.py - Handles the message with reactions (This file works perfectly)
• reaction.py - 'Listen' to the reactions to the message
import discord
import asyncio
import emoji
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix='/',preload=True)
class Reaction(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
guild_id = payload.guild_id
guild = self.client.get_guild(guild_id)
user_id = payload.user_id
user = self.client.get_user(user_id)
message_id = payload.message_id
channel = self.client.get_channel(payload.channel_id)
emoji = payload.emoji.name
if message_id == 809523588721934336 and emoji == "🐍" and user_id != 799612948213399572:
message = await channel.fetch_message(message_id)
await message.remove_reaction("🐍", user)
dev = get(guild.roles, id=799632281639321632)
await guild.add_roles(dev)
def setup(client):
client.add_cog(Reaction(client))
I think it makes sense, how are you supposed to add a role to a guild? You must add it to a discord.Member instance, you can get it with payload.member
dev = get(guild.roles, id=799632281639321632)
member = payload.member
await member.add_roles(dev)
Also remember that you must have intents.members enabled
Reference:
RawReactionAddEvent.member
Member.add_roles
In the API reference you can see that Guild does not have the method add_roles. Members do have that method.
I am coding a bot to find users with the 'Admin' role on my discord server and do print information (admin username) and store all roles in a list peopleWithRole:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
role_name = "Admin"
peopleWithRole = []
#bot.event
async def on_ready():
print("Logged in as")
print(bot.user.name)
print("------")
role = discord.utils.find(
lambda r: r.name == role_name, guild.roles)
for user in guild.members:
if role in user.roles:
peopleWithRole.append(user)
bot.run("My token")
However, when I run this, returns error 'guild' is not defined. I am just starting out with discord python module. How should I use client or bot in this situation?.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
role_name = "Admin"
peopleWithRole = []
#bot.event
async def on_ready():
print("Logged in as")
print(bot.user.name)
print("------")
guild = bot.guilds[0]
role = discord.utils.find(
lambda r: r.name == role_name, guild.roles)
for user in guild.members:
if role in user.roles:
peopleWithRole.append(user)
bot.run("My token")
In your find call you reference guild.roles but have never defined guild. You need to select the guild (I believe guilds is a member of bot)
This is a fairly basic python error to debug, and any IDE would identify what is wrong. I suggest you look up some tutorials on how to debug.
I'm making a bot with python and I need help with two things.
Making a welcome message for users that include mentioning the user and mentioning the channel
Making a command that will remove the role "Unverified" and add 4 other roles. I also need it to send a message in the verification channel to make sure the person has been verified and send an embed in general chat telling the user to get self roles.
Well you could try
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix=".")
confirmEmoji = '\U00002705'
#client.event()
async def on_ready():
print("[Status] Ready")
#client.event()
async def on_member_join(ctx, member):
channel = get(ctx.guild.channels,name="Welcome")
await channel.send(f"{member.mention} has joined")
#client.command()
async def ConfirmMessage(ctx):
global confirmEmoji
message = await ctx.send("Confirm")
await message.add_reaction(emoji=confirmEmoji)
def check(reaction, user):
if reaction.emoji == confirmEmoji:
return True
else:
return False
while True:
try:
reaction, user = await client.wait_for("reaction_add", check=check, timeout=10)
roleToRemove = get(ctx.guild.roles,name="unverified")
memberToRemoveRole = get(ctx.guild.members,name=user.display_name)
await memberToRemoveRole.remove_roles(roleToRemove)
Now all you have to do is go to the channel and enter .ConfirmMessage
I am looking for a way to allow a user to move him or her self and another user to a different voice channel. I already got the command to work for the author of the message, but I am having trouble finding out a way to move another user in the same message. The idea is that the user would be able to type "n!negotiate [Other User]" and it would move the author and the other user to the Negotiation channel.
I would love some help with how I might be able to do this. The code is provided below excluding the tokens and ids.
Code:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client() #Initialise Client
client = commands.Bot(command_prefix = "n!") #Initialise client bot and prefix
#client.event
async def on_ready():
print("Logged in as:")
print(client.user.name)
print("ID:")
print(client.user.id)
print("Ready to use!")
#client.event
async def on_message(check): #Bot verification command.
if check.author == client.user:
return
elif check.content.startswith("n!check"):
await client.send_message(check.channel, "Nations Bot is online and well!")
async def on_message(negotiation): #Negotiate command. Allows users to move themselves and other users to the Negotiation voice channel.
if negotiation.author == client.user:
return
elif negotiation.content.startswith("n!negotiate"):
author = negotiation.author
voice_channel = client.get_channel('CHANNELID')
await client.move_member(author, voice_channel)
client.run("TOKEN")
You should use discord.ext.commands. You're importing it, but not actually using any of the features.
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix = "n!") #Initialize bot with prefix
#bot.command(pass_context=True)
async def check(ctx):
await bot.say("Nations Bot is online and well!")
#bot.command(pass_context=True)
async def negotiate(ctx, member: discord.Member):
voice_channel = bot.get_channel('channel_id')
author = ctx.message.author
await bot.move_member(author, voice_channel)
await bot.move_member(member, voice_channel)
bot.run('TOKEN')
Here we use a converter to accept a Member as input. Then we resolve the author of the message from the invocation context and move both Members to the voice channel.