I typed !mycommand2 [name] [role] because it didn't come out even when I typed command !캐릭터생성 [name] [role], but it's still the same. Why? And description's role(Is it like an annotation? Explain to the developer what command this is without a role?) and...I also wonder about command hidden.
char = I want to mack a instance.....char.py has class char.
import discord, asyncio
import char
from discord.ext import commands
intents=discord.Intents.all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!',intents=intents,help_command=None)
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("언성듀엣!"))
#bot.command(name="테스트", description="테스트용 함수", hidden=False) #set hidden to True to hide it in the help
async def mycommand1(ctx, argument1, argument2):
await ctx.channel.send ("{} | {}, Hello".format(ctx.author, ctx.author.mention))
await ctx.author.send ("{} | {}, User, Hello".format(ctx.author, ctx.author.mention))
char_num = 1
#bot.command(name="캐릭터생성", description="테스트용 함수", hidden=False) #set hidden to True to hide it in the help
async def mycommand2(ctx, context1, context2):
global char_num
globals()['char_{}'.format(char_num)]=char(name=context1,Sffter=context2,username=ctx.author.name)
char_num+=1
await ctx.message.channel.send ("done", context1,"!")
client.run('-')
Change the function name to the command name
async def urcommandname(ctx,arg1,arg2):
Related
I'm trying to write a Discord Bot including a command for creating a poll like this: (The amount of options can be different)
/poll Is this bot working? <> Yes No Maybe
Then it already looks good:
(https://i.ibb.co/p3bmK5K/botbuttons.png)
However, I can't find out how to react on a button click (call the onpollbuttonclick(button) function.
Here's the relevant part of my code:
import nextcord
from nextcord.ext import commands
bot = commands.Bot(command_prefix="/")
#bot.command(name="poll")
async def poll(ctx, *, all):
separator = all.find("<>")
text = all[0:separator]
newtext = ""
for i in text:
newtext += i
options = all[separator+2:len(all)].split()
pollbuttons = nextcord.ui.View()
async def onpollbuttonclick(button):
votestatus[button] += 1
await ctx.send("Vote accepted!")
votestatus = {}
for i in options:
pollbuttons.add_item(nextcord.ui.Button(style=nextcord.ButtonStyle.red, label=i))
votestatus[i] = 0
myembed = nextcord.Embed(title="Poll")
myembed.add_field(name="\u200b", value=newtext, inline=False)
await ctx.send(embed=myembed, view=pollbuttons)
bot.run("mytoken")
if you want to create a Button with a callback function try this. This is a little bit more work than with decorators, but you can change the labels on runtime.
I hope it does the job because I didn't try it by myself.
import nextcord
from nextcord.ext import commands
bot = commands.Bot(command_prefix="/")
class Poll_Button(nextcord.ui.Button):
def __init__(self,label):
self.super.init(custom_id="yourcustomid",
label=label,
style=nextcor.ButtonStlyle.red)
async def callback(self,interaction:nextcord.Interaction):
await interaction.send("Vote accepted")
class Poll_View(nextcord.ui.View):
def __init__(self,options:List[str]):
self.super.init()
for option in options:
self.add_item(Poll_Button(option))
#bot.command(name="poll")
async def poll(ctx,*,all):
separator = all.find("<>")
text = all[0:separator]
newtext = ""
for i in text:
newtext += i
options = all[separator+2:len(all)].split()
myembed = nextcord.Embed(title="Poll")
myembed.add_field(name="\u200b", value=newtext, inline=False)
await ctx.send(embed=myembed, view=Poll_View(options)
bot.run("mytoken")
With a decorator, it looks something like this
#nextcor.ui.button(parameter):
async def funcname(button,interaction):
await interaction.send("Vote accepted")
I'm using MongoDB to run an Economy system for my Discord Bot hosted on Heroku, it was recently working fine until I tried to move it to a cog of it's own in an effort to clean up my bot however I think I've done something wrong as I'm getting the follow error. I would much appreciate if somebody could point out what I've done wrong in this situation.
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: NameError: name 'open_account' is not defined
import discord
from discord.ext import commands
import random
from datetime import datetime
from datetime import date
from datetime import timedelta
import asyncio
import time
import os
import psycopg2
import pymongo
from pymongo import MongoClient
from discord.ext import tasks
cluster = MongoClient("securelinkhere")
db = cluster["SGBot"]
collection = db["SGBot"]
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def balance(self, ctx):
await open_account(ctx.author)
discorduserid = ctx.author.id
document = collection.find_one({"userid":discorduserid})
print(document)
wallet_amt = document["points"]
em = discord.Embed(title = f"{ctx.author.name}'s balance", colour = discord.Colour.red())
em.add_field(name = "Wallet", value = wallet_amt)
await ctx.send(embed = em)
#commands.command()
#commands.cooldown(1, 14400, commands.BucketType.user)
async def work(self, ctx):
await open_account(ctx.author)
discorduserid = ctx.author.id
earnings = random.randrange(1000)
await ctx.send(f"You went to work and earned {earnings} coins!")
doc = collection.find_one({"userid":discorduserid})
total_earnings = doc["points"] + earnings
results = collection.update_one({"userid":discorduserid}, {"$set":{"points":total_earnings}})
#work.error
async def work_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
timerem = str(timedelta(error.retry_after/86400)).split(".")[0]
msg1 = 'This command is on cooldown, please try again in '
msg2 = msg1 + timerem
await ctx.send(msg2)
else:
raise error
async def open_account(self, user: discord.User):
discorduserid = user.id
doc = collection.find_one({"userid": discorduserid})
if doc != None:
print(doc)
else:
print(doc)
new_entry = ({"userid":discorduserid, "points":0})
collection.insert_one(new_entry)
def setup(bot):
bot.add_cog(Economy(bot))
Since you created the function open_account in the class Economy, and you are calling it from inside said class, you need to do self.open_account(...) where self by convention, if passed into the function, refers to the class itself.
How can I edit embed with emoji buttons in discord.py?
I was making it like this.. but it doesn't works..
#client.event
async def on_message(message):
if message.content.startswith("!menu"):
embed=discord.Embed(color=0x00FFFF, title=f'Menu', description= f'🔴 - test1 \n🟠 - test2 \n🟡 - test3 \n🟢 - test4 \n🔵 - test5 \n🟣 - test6', timestamp=message.created_at)
embed.set_footer(text=f'-', icon_url=message.author.avatar_url)
msg = await message.channel.send(embed=embed)
await msg.add_reaction('🔴')await msg.reaction_add('🟠')
await msg.add_reaction('🟡')
await msg.add_reaction('🟢')
await msg.add_reaction('🔵')
await msg.add_reaction('🟣')
if str(msg.add_reaction) == '🔴':
embed1=discord.Embed(color=0x00FFFF, title=f'edit1', description= f'test1')
await msg.edit(embed=embed1)
I want some edit codes!!
Welcome to StackOverflow, you can use discord.ext.menus. Here's how you need to install it.
pip install git+https://github.com/Rapptz/discord-ext-menus.
Then you can do something like this.
import discord
from discord.ext import menus
class ColorMenu(menus.Menu):
def __init__(self, embed):
super().__init__(timeout=30.0, delete_message_after=True)
self.embed = embed
self.result = None
async def send_initial_message(self, ctx, channel):
return await channel.send(embed=self.embed)
#menus.button('🔴')
async def red_button(self, payload):
# do what ever you want with this.
# right now I'm going to just edit the message
self.embed.description = 'test1'
self.embed.title = 'title1'
self.message.edit(embed=self.embed)
# do the same thing for other reactions
Then make a new command and instantiate the class, like this:
#bot.command()
async def menu(ctx):
color_menu = ColorMenu()
color_menu.start(ctx)
And you're done.
Good luck with your bot.
I'm trying to do a multiple choice button / reaction in discord using python (discord.py) -- something similar to the image below:
For example when it reacts to 2️⃣, that shows page 2, when it reacts to 3️⃣, that shows page 3 ...
Could anyone help me, please?
import discord
from discord.ext import commands
class Wiki(commands.Cog):
def __init__(self,bot):
self.bot=bot
#commands
#commands.command(name="wiki",aliases=["w"])
async def wiki(self,ctx):
page1=discord.Embed(
title='Page 1/3',
description='Description1',
colour=discord.Colour.orange()
)
page2=discord.Embed(
title='Page 2/3',
description='Description2',
colour=discord.Colour.orange()
)
page3=discord.Embed(
title='Page 3/3',
description='Description3',
colour=discord.Colour.orange()
)
pages=[page1,page2,page3]
message= await ctx.send(embed=page1)
await message.add_reaction('1️⃣')
await message.add_reaction('2️⃣')
await message.add_reaction('3️⃣')
emoji=""
if emoji=="1️⃣":
await message.edit_message(message,embed=pages[0])
if emoji=="2️⃣":
await message.edit_message(message,embed=pages[1])
if emoji=="3️⃣":
await message.edit_message(message,embed=pages[2])
def setup(bot):
bot.add_cog(Wiki(bot))
Take a look at the documentation for wait_for, which is how you should treat this kind of case. I won't spoonfeed you the code though, you should give it a fair shot yourself first.
Also, discord.py already has something built-in for embeds that change pages automatically based on reactions called menus, so it'll probably be easier to just use that instead of re-implementing it yourself.
Answering my own question.
I know it's not the best answer, but it works XD.
Any suggestion will be well accepted. Thank you all so much for your help.
import asyncio
import discord
from discord.ext import commands
class Wiki(commands.Cog):
def __init__(self,bot):
self.bot=bot
#commands
#commands.command(name="wiki",aliases=["w"])
async def wiki(self,ctx):
first_run = True
while True:
if first_run:
page1=discord.Embed(title='Page 1/3',description='Description1',colour=discord.Colour.orange())
first_run=False
msg = await ctx.send(embed=page1)
reactmoji = ["1️⃣","2️⃣","3️⃣"]
for react in reactmoji:
await msg.add_reaction(react)
def check_react(reaction, user):
if reaction.message.id != msg.id:
return False
if user != ctx.message.author:
return False
if str(reaction.emoji) not in reactmoji:
return False
return True
try:
res, user = await self.bot.wait_for('reaction_add', check=check_react)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if user != ctx.message.author:
pass
elif '1️⃣' in str(res.emoji):
print('<<1️⃣>>')
await msg.remove_reaction("1️⃣",user)
await msg.edit(embed=page1)
elif '2️⃣' in str(res.emoji):
print('<<2️⃣>>')
page2=discord.Embed(title='Page 2/3',description='Description2',colour=discord.Colour.orange())
await msg.remove_reaction("2️⃣",user)
await msg.edit(embed=page2)
elif '3️⃣' in str(res.emoji):
print('<<3️⃣>>')
page3=discord.Embed(title='Page 3/3',description='Description3',colour=discord.Colour.orange())
await msg.remove_reaction("3️⃣",user)
await msg.edit(embed=page3)
def setup(bot):
bot.add_cog(Wiki(bot))
im pretty new to python so i thought a good learning project would be to create a discord bot for a personal server, i have a few commands that only i as the owner of the bot can access but i would like to be able to toggle that access with a command so that my friends can also use them but i have a problem, this is the piece of the code giving me an error:
MyID = '<#xxxxxxxxxxxxxxxx>'
FFA = False
class TestCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
def IDCheck(ctx):
return ctx.message.author.id == xxxxxxxxxxxxxxxxxxxxxx
#commands.command()
async def ToggleFFA(ctx):
if FFA == False:
FFA = True
print (FFA)
await message.channel.send('All user can now use owner locked commands')
if FFA == True:
FFA = False
print (FFA)
await message.channel.send('All user can no longer use owner locked commands')
###########################################################################
#commands.command()
if FFA == False:
#commands.check(IDCheck)
async def FFATest(self, ctx, *, question):
loopnumber = 0
while spamnumber < int(question):
await ctx.send('Test' + MyID);
await asyncio.sleep(1)
loopnumber += 1
print ({loopnumber})
if FFA == True:
async def LoopTest(self, ctx, *, question):
loopnumber = 0
while loopnumber < int(question):
await ctx.send('Test' + MyID);
await asyncio.sleep(1)
loopnumber+= 1
print ({loopnumber})
###########################################################################
i get an invalid syntax error within the highlighted piece of code. If anyone knows a simpler way of toggling the access or a way that i can correct the error i would really appreciate it.
thanks in advance.
You can specify a bot_check_once method that will be used as a check on all commands from the bot. We can then have an attribute of the cog that controls which mode we are in:
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.owner_only = True
async def bot_check_once(self, ctx):
app = await self.bot.application_info()
if self.owner_only:
return ctx.author == app.owner
else:
return True
#commands.command()
async def all_users(self, ctx):
self.owner_only = False
#commands.command()
async def just_owner(self, ctx):
self.owner_only = True
Well you could add a check method outside. Here is an example.
def FFA_Enabled(ctx):
global FFA
if commands.is_owner():
return True
else:
return FFA
#commands.check(FFA_enabled):
async def SomeCommand(self, ctx:Context):
ctx.send("Message")
This Should work
if you don't know what ctx:Context means
It derives ctx from the type Context(i use it for autofill) if you wanna you is i suggest you type this:
from discord.ext.commands import Context
You can use a LIST for this, Inside that you can store the USER ID and Status ID.
Note: This is a just snippet to give you an idea, The ID Will reset when the script is restarted, I recommend you to save it in a file and load it from there.
You can also use a function to return True/False based on the USER ID instead of writing a bunch of code in each command.
users = []
status = 'Global'
#commands.is_owner()
#commands.command()
async def add_user(self,ctx,user:discord.User):
global users
id = user.id
await ctx.send(f'{user.name} has been added into the mod list.')
return users.append(id)
#commands.is_owner()
#commands.command()
async def change_status(self,ctx):
global status
if status == 'Global':
status = 'Local'
elif status == 'Local':
status = 'Global'
await ctx.send(f'Status has been changed to {status}')
return status
#commands.command()
async def test_command(self,ctx):
global status
global users
#IF Status is Local
if status == 'Local':
if ctx.user.id in users:
#ALLOW THE USERS' WHOS' ID IS IN THE LIST
pass
else:
#EXIT THE FUNCTION IF USER NOT IN THE LIST
return
#IF The status is Global
else:
#ALLOW THE COMMAND IF IT'S GLOBAL
pass