name 'guild' is not defined - python

 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.

Related

Python discord bot

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)

Make discord.py bot react to emoji added in dm

I'm trying to make a simple test bot that could do something when a reaction is added to a message that the bot send to the user dm. Now I'm stuck after the intial trigger that send the dm and add the emoji to react to. Any help to make that work?
import discord
import time
client = discord.Client()
intents = discord.Intents.default()
intents.members = True
#client.event
async def on_ready():
print("testing")
#client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 968972405206827028:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == '✅':
role = discord.utils.get(guild.roles, name='role')
user = await client.fetch_user(payload.user_id)
embedVar = discord.Embed(title="Some order", description='Welcome to your order, %s \n Please select your payment method of choice:' % (payload.member.name), color=0x00ff00)
dm = await user.send(embed=embedVar)
await dm.add_reaction(some_emoji)
await dm.add_reaction(some_emoji)
client.run("MY_TOKEN")
Your code is trying to get a particular guild from the payload guild_id attribute, which in a DM doesn't exist.
In discord.py, DMs aren't considered guilds, hence there is no particular ID. If you're setting this system up for a particular server, I'd recommend you use something as client.get_guild(your_id_here), which will give you the Guild object if the bot is in that guild.
In short terms, guild_id is invalid since DMs are not guilds (servers). Find a way to work around that.
My solutions would be:
is it for a specific server? Get the guild by ID and perform your operations
is it for any server? Perhaps use databases to store IDs and perform accordingly
Hope this helps!

How do I give roles to a person that reacted to my message?

In the code below I am trying to give a role to a person whenever they react to my message but this code throws me an error saying that 'int' object has no attribute 'id' the code says that the problem is with this code: await user.add_roles(user.guild.id, user.id, role, reason='reason') how do I solve this issue?
import discord
from discord.ext import commands
import random
client = discord.Client()
#client.event
async def on_ready():
print('ready')
#client.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
await channel.send(f'{user.name} has reacted by using {reaction.emoji} emoji, his message was {reaction.message.content}')
role = discord.utils.get(user.guild.roles, name = 'Test_Bot')
await user.add_roles(user.guild.id, user.id, role, reason='reason')
client.run('TOKEN')
As Dominik said, you do not need user.guild.id, user.id if you say await user.add_roles. What is happening is that it is trying to use the user.id (an integer) you passed instead of the user object you use when calling the function to begin with: await user.add_roles(...).
So, get rid of await user.add_roles(user.guild.id, user.id, role, reason='reason'), and make it just: await user.add_roles(role).
Fixed code should be:
import discord
from discord.ext import commands
import random
client = discord.Client()
#client.event
async def on_ready():
print('ready')
#client.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
await channel.send(f'{user.name} has reacted by using {reaction.emoji} emoji, his message was {reaction.message.content}')
role = discord.utils.get(user.guild.roles, name = 'Test_Bot')
await user.add_roles(role, reason='reason')
client.run('TOKEN')
TL;DR: Discord.py expects the full member object when you use add_roles(). You give it the integer of the member's ID instead.

Discord.py | How can i add role to members?

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'm getting no results while trying to make a reaction bot with discord.py

My code is:
#client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 768549092674502666:
if payload.emoji.name == 'white_check_mark':
role = '<:Member:765291826151555104>'
await member.add_role(role)
and i'm getting no results from the debugger or except when the bot adds a reaction or logs on which are other code completely inaccosiated with this part of the code.
In the new version of discord.py(1.5.x), there're some updates about Intents. Intents are like permissions and for using some of the events or getting members, channels etc. you need to define it before you define the client = discord.Bot(prefix='').
Then, you need to define the member to add role. You can simply do member = payload.member.
And also you need to get role with discord.utils.get(). You can't define a role with string.
import discord
intents = discord.Intents().all()
client = discord.Bot(prefix='', intents=intents)
#client.event
async def on_raw_reaction_add(payload):
if payload.message_id == 768549092674502666 and payload.emoji.name == 'white_check_mark':
guild = client.get_guild(guild id)
role = discord.utils.get(guild.roles, name="role's name")
await payload.member.add_roles(role)
If you want to get more information about Intents, you can check the API References

Categories

Resources