Adding Roles In Slash Commands (Discord.Py) - python

#tree.command(name = 'redeem', description = 'Redeems A Members Key')
async def redeem(interaction: discord.Interaction, key: str, member:discord.Member):
with open("bkeys.txt") as f:
if key in f.read():
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Sorry, this key has been blacklisted")
await interaction.response.send_message(embed=em)
return 0
with open("keys.txt") as f:
if key in f.read():
role = interaction.guild.get_role(1071561081685811210)
await member.add_roles(member, role)
em = discord.Embed(color=0x008525)
em.add_field(name="Key Redeemed", value="Key has now been redeemed")
await interaction.response.send_message(embed=em)
f = open("ukeys.txt", "w")
f.write(key)
f.write('\n')
else:
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Inputed key has already been used!")
await interaction.response.send_message(embed=em)
Error
**This has been a command I have been trying to work on its just the add roles will not work, btw im new to python so I don't know much sorry, so if anyone could just drop the code please.
**
I tried changing the (1071561081685811210) to my role name ("Buyer") and asking for help but I didn't understand.

like bruh has said you should change
member.add_roles(member,role)
to
member.add_roles(role)

Related

discord.py updating a document in mongodb

I'm trying to make a command that allows the user to update a reason on a warn to something else and I don't know how to update documents in mongodb
check = list(warndb.warn_logs.find({"case_id": caseid}))
for w in check:
reason = w.get('reason')
caseid = w.get('case_id')
change = {{"reason": reason}, {"$set": {"reason": update}}}
w.update(change, upsert=False)
embed = discord.Embed(color=embedcolor, title="Successfully updated reason", description=f"Updated reason for case {caseid}")
embed.add_field(name="**Before:**", value=f"{reason}", inline=False)
embed.add_field(name="**Updated To:**", value=f"{update}", inline=False)
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed)
return
Here's the main code that I have to update documents but I'm getting a couple of errors and I don't know how to update documents. please help
So please provide full trace back but here is the code for update your mongo also check documention : Mongo doc.
In a cog it could look like this - arg would be the case id eg "!update_warn 123" then the arg would be 123 and also the case id
cluster = MongoClient('Your mongo link')
collection_name = cluster["Database Name"]["Collection Name"]
#commands.command()
async def update_warn(self,ctx,arg):
check = collection_name.find_one({"case_id": arg})
if check is None:
await ctx.reply("No Case was found!")
else:
reason = check['reason']
caseid = check['case_id']
update = "Your Updated Reason"
collection_name.update_one({'case_id':arg},{'$set':{'reason': update}})
embed = discord.Embed(color=embedcolor, title="Successfully updated reason", description=f"Updated reason for case {caseid}")
embed.add_field(name="**Before:**", value=f"{reason}", inline=False)
embed.add_field(name="**Updated To:**", value=f"{update}", inline=False)
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed)

Discord Py Bot - json file is being written to but does not save after reload

I have a json load/save/dump function to count how many time a single word is said in a specific channel. It works great, but I lose the data after reboot of the bot. Below is my code.
def load_counters():
with open('cup.json', 'r') as f:
counters = json.load(f)
return counters
def save_counters(counters):
with open('cup.json', 'w') as f:
json.dump(counters, f)
if message.channel.id == 709551578612498453:
if message.content == ('cup'):
counters = load_counters()
counters["cup"] += 1
save_counters(counters)
return
else:
cup_meta = client.get_channel(709984510678269982)
cup_channel = client.get_channel(709551578612498453)
await cup_meta.send(message.author.mention + ' has violated the sacred rules of Cup')
await message.delete()
await cup_channel.send('cup')
return
with open('cup.json', 'r') as f:
counters1 = json.load(f) # Open and load the file
totalcup = counters1['cup']
if message.content == ('!totalcup'):
await message.channel.send(f"Cup has been said {totalcup} times since Bender reset me.")
Here is the json file - right now if I were to run !totalcup, the bot spits out '13' but the file says 0. Not sure if I am missing something as I am new to code.
{
"cup": 0
}
I just figured it out. The code does work as intended, it is a problem with how my host (Heroku) operates. There isn't anything I can do until I find a new hosting situation.

Dislash.py Error with Discord Commands 'str' object has no attribute 'type'

I am getting an error when using dislash.py with commands in discord. The code is essentially taking data from discord that the user puts in a command and it posts it into a new row in google sheets. The error is below. Does anyone have an idea why this is occurring? Thank you in advance.
Here is my main code for the command:
#slash.command(
name="hi",
description="Complete this command to win",
options=[
Option(
"vara",
description="What is your favorite color",
type=OptionType.STRING,
required=True
)
],
guild_ids=test_guilds)
async def floor(inter,vara):
role_names = [role.name for role in inter.author.roles]
print(role_names)
if inter.channel.id != 933170181486805042 or "+" not in role_names:
await inter.reply('You can not perform this command because you are not the winner.')
elif inter.channel.id == 933170181486805042:
global wl
if "Superstar" in role_names:
wl='4'
elif "Winner" in role_names:
wl='2'
elif "Loser" in role_names:
wl='1'
else:
wl='0'
username = inter.author.mention
user = inter.author.name
userid = inter.author.id
insertRow = [user, username, vara, wl]
sheet.append_row(insertRow, table_range="A1")
await inter.reply('Thanks, ' + username + '')
role = discord.utils.get(inter.author.roles, name='+')
await inter.author.remove_roles(role)

Getting emoji object to unicode

Right now im my journey of discordbot making, I'm tackling reaction roles! I think I have most everything setup, but I can't seem to find a way to get from an emoji object to an emoji unicode, so I can compare them and add the reaction. Here's what I have so far:
#bot.event
async def on_raw_reaction_add(payload):
print(payload)
channel = bot.get_channel(payload.channel_id)
emoji = payload.emoji
print(emoji.id)
#bot.command(pass_context=True)
async def reactionrole(ctx, title:str, description:str, name:str, value:str):
title = ''.join(title)
description = ''.join(description)
name = ''.join(name)
value = ''.join(value)
embed = discord.Embed(colour = discord.Colour.teal(), title = title, description = description)
embed.add_field(name = name, value = value, inline=False)
message = await ctx.send(embed = embed)
with open("reactionroles.json", 'r') as f:
data = json.load(f)
addon = {"guild-id" : ctx.guild.id}, {"message-id" : message.id}, {"roles" : []}, {"emojis" : []}
data[ctx.guild.id] = addon
with open("reactionroles.json", 'w') as f:
json.dump(data, f)
#bot.command(pass_context=True)
async def reactionadd(ctx, emoji, *role:str):
role = ''.join(role)
with open("reactionroles.json", 'r') as f:
data = json.load(f)
message_id = data[str(ctx.guild.id)][1]['message-id']
message_id = int(message_id)
message = await ctx.channel.fetch_message(message_id)
await message.add_reaction(emoji)
role = discord.utils.get(ctx.guild.roles, name=role)
data[str(ctx.guild.id)][3]['emojis'].append(emoji)
print(role)
data[str(ctx.guild.id)][2]['roles'].append(str(role))
with open("reactionroles.json", 'w') as f:
json.dump(data, f, indent=4)
So the command reactionrole creates the embed, and writes some placeholder data into a json file. Afterwards, the reactionadd command adds the emoji unicode to a json array, and the role to a different json array. When on a reaction add, in on_raw_reaction_add(payload), payload only has the name of the emoji, and not the unicode. Because of this, I', not able to compare the two to see what role goes to what emoji. I can't save the origional, in reactionadd because I would run into problems in on_reaction_add. I'm lost on getting the unicode from the payload this is my final reach out. Here's what's inside payload:
<RawReactionActionEvent message_id=759903170721087508 user_id=146348630926819328 channel_id=754904403710050375 guild_id=665787149513261057 emoji=<PartialEmoji animated=False name='�😋' id=Non
event_type='REACTION_ADD' member=<Member id=146348630926819328 name='Chai' discriminator='6396' bot=False nick=None guild=<Guild id=665787149513261057 name="ChaiBot's Playground" shard_id=None chunked=True member_count=34>>>
From an Emoji object you can get the unicode character from emoji.name, or if you are looking for the unicode name you can use the python unicodedata library:
import unicodedata
unicodedata.name(emoji.name)
I have realized my error! I was able to compare the unicode from reactionadd to payload.emoji the entire time! I was not able to see originally though, that vs code shows the unicode as an emoji (in terminal), and not as the string. That makes much more sense now! Thanks to all they helped!

How to remove bot pagination response in discord.py

So I am using disputils and I've made a pagination embed. however, after it gets inactive the reactions get auto removed by the bot. I want to make the bot remove the whole embed but I've tried a lot of things such as using delete_after=(float) and even asyncio but it doesn't seem to be working.
#commands.group(aliases = ['ra'])
async def red(self, ctx):
if ctx.invoked_subcommand is None:
default = discord.Embed(title="`test`",color=discord.Colour.dark_red())
default.set_image(url="foo")
default.set_footer(text="Image by| user")
v1 = discord.Embed(title="example", description='test', color=discord.Colour.dark_red())
v1.set_footer(text="Info taken from| website")
v2 = discord.Embed(title="spam", description="foo" ,color=discord.Colour.dark_red())
v2.set_footer(text="Info taken from| website")
embeds = [
default,
v1,
v2,
]
paginator = BotEmbedPaginator(ctx, embeds)
await paginator.run()
I tried using delete_after(float) inside the paranthesis of await paginator.run() doesn't work. tried using it asycnio format and got an error Instance of 'BotEmbedPaginator' has no 'delete' member. Any help would be appreciated.
Just use DiscordUtils
Here is an example:
#commands.command()
async def paginate(self, ctx):
embed1 = discord.Embed(color=ctx.author.color).add_field(name="Example", value="Page 1")
embed2 = discord.Embed(color=ctx.author.color).add_field(name="Example", value="Page 2")
embed3 = discord.Embed(color=ctx.author.color).add_field(name="Example", value="Page 3")
paginator = DiscordUtils.Pagination.CustomEmbedPaginator(ctx, remove_reactions=True)
paginator.add_reaction('⏮️', "first")
paginator.add_reaction('⏪', "back")
paginator.add_reaction('🔐', "lock")
paginator.add_reaction('⏩', "next")
paginator.add_reaction('⏭️', "last")
embeds = [embed1, embed2, embed3]
await paginator.run(embeds)

Categories

Resources