my code does not work. Everytime I try to fix it it does not work. This is what I have finished at and it says that the command has not been found. Anyone got a solution?
#bot.command()
async def suggest(self, ctx, *,suggestion):
await ctx.channel.purge(limit = 1)
channel = discord.utils.get(ctx.guild.text_channels, name = '💡suggestions')
suggestEmbed = discord.Embed(colour = 0xFF0000)
suggestEmbed.set_author(name=f'Suggested by {ctx.message.author}', icon_url = f'{ctx.author.avatar_url}')
suggestEmbed.add_field(name = 'Suggestion', value = f'{suggestion}')
message = await ctx.send(embed=suggestEmbed)
await message.add_reaction('✅')
await message.add_reaction('❌')
First of all, a better way to delete command usage is await ctx.message.delete()
Second, you should use client.get_guild() and client.get_channels() instead of channel = discord.utils.get(ctx.guild.text_channels, name = '💡suggestions')
Also, if you could include any errors, it would be helpful.
Related
I made a moderator bot but when i launch the code python writes "Process finished with exit code 0". Please check my if something wrong.
import discord
import config # Config is a another py file
client = discord.Client()
#client.event
async def on_message(message):
id = client.get_guild(config.ID)
badwords = ["testword", "testword2"]
unwarnusers = (config.unwarnusers)
for word in badwords:
if word in message.content.lower():
if str(message.author) not in unwarnusers:
warnFile = open("E:/vp2/warns.txt", "a")
warnFile.write(str(message.author.mention) + "\n")
warnFile.close()
warnFile = open("E:/vp2/warns.txt", "r")
warnedUsers = []
for line in warnFile:
warnedUsers.append(line.strip())
warnFile.close()
warns = 0
for user in warnedUsers:
if str(message.author.mention) == user:
warns += 1
if warns > 4:
mutedRole = discord.utils.get(message.guild.roles, name = "JB-MUTED")
await message.author.add_roles(mutedRole)
channel = client.get_channel(959128819137146900)
await channel.send(f"\nUser {message.author.mention} made something bad. \nHe writes:\n{message.content}\nThis happened in {message.channel}\n Warns: {warns}")
Add client.run('token') to the bottom of your code.
I'm trying to add a few subcommands to my code to make everything clearer.
Unfortunately, I have the problem that certain sections of code are simply not executed.
My Code:
#commands.group(invoke_without_command=True)
async def server(self, ctx):
created = ctx.guild.created_at
x = re.search("^.*:", str(created))
x = x.group()
x = x[:-6]
me = ctx.guild
embed = discord.Embed(title = f"Information about ``{ctx.guild}``", description=me.description, color = 0xf7fcfd, timestamp=ctx.message.created_at)
embed.add_field(name="__Information__", value=f"**Owner:** {me.owner}\n**Name:** {me.name}\n**ID:** {me.id}\n**Region:** {me.region}\n**Created at:** {x}", inline=False)
embed.add_field(name="__Server Information__", value=f"**Member**: {len(me.members)}\n**Roles:** {len(me.roles)}\n**Max Emojis:** {me.emoji_limit}\n**Emojis:** {len(me.emojis)}", inline=False)
embed.add_field(name="__Channel Information__", value=f"**Text-Channel:** {str(len(me.text_channels))}\n**Voice-Channel:** {str(len(me.voice_channels))}\n**AFK-Channel:** ``{me.afk_channel}``\n**AFK-Timeout:** ``{me.afk_timeout}sec``")
embed.set_footer(text=f"{ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
embed.set_thumbnail(url=me.icon_url)
embed.set_image(url=me.banner_url)
await ctx.send(embed=embed)
# SERVER AVATAR
#server.command()
async def avatar(self, ctx):
if not ctx.guild.icon:
embed = discord.Embed(title="Server has no avatar!", color=0xf7fcfd)
return await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f"Avatar of {ctx.guild.name}", color=0xf7fcfd)
embed.set_image(url=ctx.guild.icon_url_as(size=1024))
await ctx.send(embed=embed)
# SERVER BANNER
#server.command()
async def banner(self, ctx):
if not ctx.guild.banner:
embed = discord.Embed(title="Server has no banner!", color=0xf7fcfd)
return await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f"Banner of {ctx.guild.name}", color=0xf7fcfd)
embed.set_image(url=ctx.guild.banner_url_as(format='png'))
await ctx.send(embed=embed)
The problem is that the command ?server avatar does not provide any output. The commands ?server and ?server banner work perfectly.
Am I using the subcommands incorrectly or why do I get no output?
The reason why it didn't work is that I already had another command called avatar. The Bot would always take the command (avatar) instead the subcommand (server avatar).
I'm trying to make a poll command in Discord.py but want at the end the bot to send a list of users that reacted with 1️⃣ and another list of people that reacted with 2️⃣.
This is my code so far:
async def poll(ctx, q1, q2, time : int):
await ctx.send(f"React with 1 to vote for **{q1}** and with 2 to vote for **{q2}**\n**Poll Lasts for {time} seconds**")
poll = discord.Embed(title = "Poll", color = discord.Color.blue())
poll.add_field(name = f"{q1} 1️⃣", value = "")
poll.add_field(name = f"{q2} 2️⃣", value = "")
msg = await ctx.send(embed = poll)
r1 = await msg.add_reaction("1️⃣")
r2 = await msg.add_reaction("2️⃣")
await asyncio.sleep(time)
await ctx.send("Times up! **Poll Closed**")
new_msg = discord.utils.get(client.cached_messages,id = msg.id)
users1 = await r1.reactions[0].users().flatten()
users1.pop(users1.index(client.user))
users2 = await r2.reactions[0].users().flatten()
users2.pop(users2.index(client.user))
em=discord.Embed(title=f'Votes for {q1}', description=" , ".join(user.name for user in users1),color = discord.Colour.blue())
await ctx.send(embed = em)
em=discord.Embed(title=f'Votes for {q2}', description=" , ".join(user.name for user in users2),color = discord.Colour.blue())
await ctx.send(embed = em)
And this is the error I am getting:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'reactions'
Message.add_reaction returns None, you can't use these two lines
r1 = await msg.add_reaction("1️⃣")
r2 = await msg.add_reaction("2️⃣")
Easiest approach would be to fetch the message again with the updated reactions
message = await ctx.send("Whatever")
await message.add_reaction("1️⃣")
await message.add_reaction("2️⃣")
await asyncio.sleep(10)
updated_message = await ctx.channel.fetch_message(message.id)
users1, users2 = [], []
for r in updated_message.reactions:
print(f"{str(r)} was added {r.count} times")
if str(r) == "1️⃣":
users = await r.users().flatten()
users1.extend(users)
elif str(r) == "2️⃣":
users = await r.users().flatten()
users2.extend(users)
# `users1` and `users2` are lists of users that reacted with `1️⃣` and `2️⃣` accordingly
Reference:
Messageable.fetch_message
Message.reactions
Reaction.count
Reaction.users
I know how to send embeds in discord.py but I am a little bit confused about this code
Please, anyone, help me with a sample of code for this command.
#client.command()
async def wanted(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
wanted = Image.open("wanted.jpg")
asset = user.avatar_url_as(size = 128)
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp = pfp.resize((257, 257))
wanted.paste(pfp, (99, 201))
wanted.save("profile.jpg")
await ctx.send(file = discord.File("profile.jpg"))
To send a local image in an embed:
file = discord.File("some_file_path", filename="image.png")
embed = discord.Embed()
embed.set_image(url="attachment://image.png") # Same name as in the file constructor
await ctx.send(file=file, embed=embed)
To add the pfp of the invoker to an embed
embed = discord.Embed()
embed.set_image(url=ctx.author.avatar_url)
await ctx.send(embed=embed)
When trying to save my list of reactionrole objects with pickle it gives me the error Command raised an exception: TypeError: cannot pickle 'TaskStepMethWrapper' object.
I have not tried anything because I'm not sure what TaskStepMethWrapper is. Here's my code:
#client.command()
async def reactionadd(ctx):
# await ctx.send('Please give me the ID of the message you want to have a reactionrole on.')
# msgid_var = await client.wait_for('message')
await ctx.send('Please react with the emoji you want the reactionrole to use.')
emoji_var = await client.wait_for('reaction_add')
# await ctx.send('Please give me the ID of the role you want the reactionrole to give.')
# roleid_var = await client.wait_for('message')
if not os.path.isfile('reactionrole.obj'):
rrf = open('reactionrole.obj', 'xb')
rrf.close()
rrf = open('reactionrole.obj', 'rb+')
if os.stat('reactionrole.obj').st_size == 0:
rrobj = []
else:
rrobj = pickle.load(rrf)
emoji_var = emoji_var[0]
rrobj.append(reactionrole(749316751212150965, emoji_var, 749317419255857232))
pickle.dump(rrobj, rrf)
rrf.close()
class reactionrole:
def __init__(self, msgid, emoji, roleid):
self.msgid = msgid
self.emoji = emoji
self.roleid = roleid
SO, how to fix this error? should I go on with pickle or use another serialization technique? I could write to and parse a text file myself if needed.
Turns out emoji_var[0] is an object. Simply using str() to turn it into a string fixed this.