How do I make a discord.py embed? - python

The code essentially is supposed to create an embed and for some reason it gives me the error " 'message' is not defined" (the embed will be put into anoter bot)
import discord
from discord.ext import commands
import random
from discord.ext.commands import Bot
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
channel = self.get_channel(717005397655027805)
await channel.send("I am now online")
messageContent = message.Content
if message.author == self.user:
return
#client.event
async def on_message(message):
if message.content.startswith('!hello'):
embedVar = discord.Embed(
title="Title", description="Desc", color=0x336EFF
)
embedVar.add_field(name="Field1", value="hi", inline=False)
embedVar.add_field(name="Field2", value="hi2", inline=False)
client.send_message(message.channel, embed=embedVar)
PREFIX = ("$")
bot = commands.Bot(command_prefix=PREFIX, description='Hi')
client = MyClient()
client.run('TOKEN')

As you use CLASSES AND OBJECTS or OOP for the bot you need correct syntax too. I can't really help you with than but can use normal way.
Step 1:
We will import the libraries:
import discord
from discord.ext import commands
import random
Step 2:
We will define the Prefix and Bot's variable.
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
Step 3:
We will now write the bot's on_ready() command according to your code.
#bot.event
async def on_ready():
print('Logged on as', self.user)
channel = bot.get_channel(717005397655027805)
await channel.send("I am now online")
The statement bot.get_channel() is being used to get the channel to send the message.
Step 4:
We will now write bot's on_message function according to your code.
#bot.event
async def on_message(message):
if message.content.startswith('!hello'):
embedVar = discord.Embed(
title="Title", description="Desc", color=0x336EFF
)
embedVar.add_field(name="Field1", value="hi", inline=False)
embedVar.add_field(name="Field2", value="hi2", inline=False)
await message.channel.send(embed=embedVar)
Step 5:
We will now create a statement to start up your bot.
bot.run("TOKEN")
Add this command at the bottom of the script.
The whole code compiled will be:
import discord
from discord.ext import commands
import random
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#bot.event
async def on_ready():
print('Logged on as', self.user)
channel = bot.get_channel(717005397655027805)
await channel.send("I am now online")
#bot.event
async def on_message(message):
if message.content.startswith('!hello'):
embedVar = discord.Embed(
title="Title", description="Desc", color=0x336EFF
)
embedVar.add_field(name="Field1", value="hi", inline=False)
embedVar.add_field(name="Field2", value="hi2", inline=False)
await message.channel.send(embed=embedVar)
This would solve your problem. If you still get any problem, please ask me in the comments. :)
Thank You! :D

Try this (based of Bhavyadeep's code):
import discord
from discord.ext import commands
import random
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#bot.event
async def on_ready():
print('Logged on as', bot.user)
# channel = bot.get_channel(717005397655027805)
# await channel.send("I am now online")
#bot.event
async def on_message(ctx):
if ctx.content.startswith('!hello'):
embedVar = discord.Embed(
title="Title", description="Desc", color=0x336EFF
)
embedVar.add_field(name="Field1", value="hi", inline=False)
embedVar.add_field(name="Field2", value="hi2", inline=False)
await ctx.channel.send(embed=embedVar)
bot.run("TOKEN")
I've simply replaced "message" with "ctx". If this still doesn't work, then try replacing bot = commands.Bot(command_prefix=PREFIX, description="Hi") with bot = commands.Bot(command_prefix=PREFIX, description="Hi", pass_context=True).
It also appears your indentation in the class MyClient is wrong, so fix that first. Make sure that async def on_message(... is in the class scope.
If all fails, try and move the code to the global scope (delete the class).

You didn't specify what message.Content is in on the on_ready() function, also you need to create the on_message() function outside of the on_ready() func, and you didn't specify what the #client decorator is, you just specified it at the end of your code.
All in all, your fixed code should look something like this
from discord.ext import commands
TOKEN = "Your token here"
PREFIX = '$'
bot = commands.Bot(command_prefix=PREFIX)
#bot.event
async def on_ready():
print('Logged on as', bot.user)
channel = bot.get_channel(717005397655027805)
await channel.send("I am now online")
#bot.command() # Usage - $hello
async def hello(ctx):
if ctx.message.author == bot.user: return
embedVar = discord.Embed(title="Title", description="Desc", color=0x336EFF)
embedVar.add_field(name="Field1", value="hi", inline=False)
embedVar.add_field(name="Field2", value="hi2", inline=False)
await ctx.send(embed=embedVar)
bot.run(TOKEN)

Related

I am having problem in making a discord bot [duplicate]

This question already has answers here:
Why does on_message() stop commands from working?
(2 answers)
Closed 9 months ago.
This is my code. #client.command() is being ignored. Please help me if you can. #client.event is working fine but #client.command() is completely being ignored. Even if I add a new command or change the current one, it just does not works. I don't even get any errors.
import discord
import os
import random
from keep_alive import keep_alive
from discord.ext import commands
paint=[0xff0000 , 0x0000ff , 0x000000 , 0x00ffff , 0xffffff , 0xffd700 , 0x4b0082]
heads_tails = 'Heads', 'Tails'
prefix = ['-']
client = commands.Bot(prefix)
client.remove_command('help')
#client.event
async def on_ready():
await client.change_presence(activity=discord.Game('with The Boys'))
print("Ready to help you.")
#client.event
async def on_message(message):
if message.content.startswith('-help'):
embedVar = discord.Embed(
title="Help arrived!",
description="Here are a list of commands for your help",
colour=(random.choice(paint)))
embedVar.add_field(name="Bot Prefix",
value="-", inline=False)
embedVar.add_field(name="Moderation Commands",
value="-help",
inline=True)
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)
embedVar.set_thumbnail(
url= "https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif"
)
await message.channel.send(embed=embedVar)
if message.content.startswith('-coinflip'):
embedVar = discord.Embed(
title="Coinflip",
description=(f'You got {random.choice(heads_tails)}'),
colour=(random.choice(paint)))
await message.channel.send(embed=embedVar)
await client.process_commands(message)
#client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
if ctx.message.author.server_permissions.administrator:
role = discord.utils.get(member.server.roles, name='Muted')
await ctx.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await ctx.send(embed=embed)
keep_alive()
client.run(os.getenv('Token'))
First of all, why didn't you make "help" and "coinflip" a bot command? Make everything possible a bot command and not the async def on_message(message)
#client.command()
async def help(ctx)
embed = discord.Embed(
title="Help arrived!",
description="Here are a list of commands for your help",
colour=(random.choice(paint)))
embedVar.add_field(name="Bot Prefix",
value="-", inline=False)
embedVar.add_field(name="Moderation Commands",
value="-help",
inline=True)
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)
embedVar.set_thumbnail(
url= "https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif"
)
await message.channel.send(embed=embed)
The issue that you are facing is that you have accidentally placed your client.process_commands(message) function inside your coinflip condition. Moving this line of code outside of the if statement should resolve your issues.
#client.event
async def on_message(message):
await client.process_commands(message)
Try to run it through shell.
I got same issue while running a simple bot , got code 0 as output but nothing output,

discord.py problems with on_member_join()

What am I doing wrong?
#bot.event
async def on_member_join(member):
print(f"{member} join")
role_1 = member.guild.get_role(start_role_id)
await member.add_roles(role_1)
I searched for answers on the forums for a long time and nothing helped.
Did you enable intents in Discord Developer Portal? while initializing bot add intents=discord.Intents.all(). Also I fixed your code.
bot = commands.Bot(command_prefix='', intents=discord.Intents.all())
#bot.event
async def on_member_join(member):
print(f"{member} join")
role1 = discord.utils.get(member.server.roles, id=role_id)
await member.add_roles(role1)
Try this:
bot = commands.Bot(command_prefix='PREFIX_HERE',
intents=discord.Intents.all())
#bot.event
async def on_member_join(member):
print(f"{member} has joined")
my_role = discord.utils.get(member.guild.roles, id=role_id)
await member.add_roles(my_role)

discord.py ctx commands do not return anything

I'm trying to use bot commands in discord so I can start using the bot prefix. I tried using ctx, but from the code that I have written, when I use .ping, it returns nothing. Anyone got any idea why?
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix= ".")
#client.event
async def on_ready():
print("Logged in") #login message
#bot.command(pass_context = True) #trying to get "test" to return from .ping
async def ping(ctx):
await ctx.channel.send("test")
#client.event
async def on_message(message):
if message.author == client.user: #testing the bot actually responds to something
return
if message.content.startswith("Hello"):
await message.channel.send("Hi")
client.run('#bot token here')
There are a lot of things wrong in your code:
Use discord.Client or commands.Bot not both
You didn't enable intents, so message.author is None, here's how:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(..., intents=intents)
Also make sure to enable privileged intents in the developer portal
You're running the client, not the bot, if you want the commands to work run the bot and get rid of client
Change the decorator of the on_message and on_ready events and add process_commands at the end of on_message:
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("Hello"):
await message.channel.send("Hi")
await bot.process_commands(message)
Here's your fixed code:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix= ".", intents=intents)
#bot.event
async def on_ready():
print("Logged in")
#bot.command()
async def ping(ctx):
await ctx.send("test")
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("Hello"):
await message.channel.send("Hi")
await bot.process_commands(message)
bot.run('#bot token here')
There are some bugs in your code that I have found.
Don’t use both discord.Client() and commands.Bot()
You need to enable intents. Go to the discord developers page then to your bot and enable both intents. Quick Link To The Developer Page On Discord
Then write this code:
intents = discord.Intents.all()
bot = commands.Bot(commands_prefix=“.”, intents=intents)
Make sure you are not using any client here.
There are even more stuff needed to fix. Since now we are using bot, change everything saying client to bot. You also have to add await bot.process_commands(message) to the end of the on_message function. Also change ctx.channel.send to just ctx.send
#bot.event
async def on_ready():
print("Logged in") #login message
#bot.command(pass_context = True) #trying to get "test" to return from .ping
async def ping(ctx):
await ctx.channel.send("test")
#bot.event
async def on_message(message):
if message.author == bot.user: #testing the bot actually responds to something
return
if message.content.startswith("Hello"):
await message.channel.send("Hi")
await bot.process_commands(message)
bot.run('#bot token here')
Just use simple ctx.send, it's common for commands,
#bot.command()
async def ping(ctx):
await ctx.send("test")

discord.py bot not joining channel

ok so here is my code
import discord
from discord.ext import commands
TOKEN = 'THIS_IS_MY_BOT_TOKEN'
client = commands.Bot(command_prefix = '.')
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
#typing cat
if message.content.startswith('!cat'):
msg = 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif'.format(message)
await client.send_message(message.channel, msg)
#I dont need sleep i need awnsers
if message.content.startswith('!sleep'):
msg = 'https://i.kym-cdn.com/entries/icons/original/000/030/338/New.jpg'.format(message)
await client.send_message(message.channel, msg)
#murica
if message.content.startswith('!murica'):
msg = 'https://www.dictionary.com/e/wp-content/uploads/2018/08/Murica_1000x700.jpg'.format(message)
await client.send_message(message.channel, msg)
if message.content.startswith('!why'):
msg = 'https://drive.google.com/file/d/1rb132Y785zUjj2RP2G-a_yXBcNK5Ut9z/view?usp=sharing'.format(message)
await client.send_message(message.channel, msg)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
#client.command(pass_context=True)
async def join(ctx):
if ctx.message.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
client.run(TOKEN)
the bot joins the sever, but when I say .join, nothing happens
the voice channel I want to join is called Club Meeting if that helps
Not entirely sure why, I have no errors when I run it. Anyone have any idea whats going on?
I think the problem is your lack of Bot.process_commands You need to put that at the end of your on_message function. That seems to be the reason your command isn't working.
From The Docs:
Why does on_message make my commands stop working?
https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working

My python code refuses to run for this discord bot I am making

Nothing works or runs
The client simply will not run and I get a blank console and I can not get the bot to respond in discord
I have ran the bot and it refuses to work
It has stopped reponding to my text input in discord chat and will not respond to it
import discord
from discord.ext import commands
import asyncio
from itertools import cycle
token = 'Dummy Token ACGT'
status = ['EpicGamerTime', 'Help', 'GamerStuff']
client = commands.Bot(command_prefix = ",")
#client.event
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def change_status():
await client.wait_until_ready()
statuses = cycle(status)
while not client.is_closed:
current_status = next(statuses)
await client.change_presence(activity=discord.Game(name=current_status))
await asyncio.sleep(2)
#client.event
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello {0.author.mention}'.format(message))
if message.content.startswith('!who is online'):
await message.channel.send('Not Sure {0.author.mention}'.format(message))
if message.content.endswith('whammy'):
await message.channel.send('response {0.author.mention}'.format(message))
client.loop.create_task(change_status())
client.run(token)
No output or error messages
You are using self as a variable in your functions. This is typically used when creating classes, which you are not doing.
Remove self from your functions and it works fine.
Also, I advise that you regenerate your bot token. Since you have included it in your question, anyone can use it to hijack your bot. Regenerate the token and do not share it with anyone.
import discord
from discord.ext import commands
import asyncio
from itertools import cycle
token = 'token'
status = ['EpicGamerTime', 'Help', 'GamerStuff']
client = commands.Bot(command_prefix = ",")
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
async def change_status():
await client.wait_until_ready()
statuses = cycle(status)
while not client.is_closed:
current_status = next(statuses)
await client.change_presence(activity=discord.Game(name=current_status))
await asyncio.sleep(2)
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author.id == client.user.id:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello {0.author.mention}'.format(message))
if message.content.startswith('!who is online'):
await message.channel.send('Not Sure {0.author.mention}'.format(message))
if message.content.endswith('whammy'):
await message.channel.send('response {0.author.mention}'.format(message))
client.loop.create_task(change_status())
client.run(token)
I removed all selfs from funcs and used client where self was used
Hope this helps
import discord
import asyncio
from discord.ext import commands
from itertools import cycle
from toke import token
status = ['EpicGamerTime', 'Help', 'GamerStuff']
client = commands.Bot(command_prefix=",")
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
async def change_status():
await client.wait_until_ready()
statuses = cycle(status)
while not client.is_closed:
current_status = next(statuses)
await client.change_presence(activity=discord.Game(name=current_status))
await asyncio.sleep(2)
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author.id == client.user.id:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello {0.author.mention}'.format(message))
if message.content.startswith('!who is online'):
await message.channel.send('Not Sure {0.author.mention}'.format(message))
if message.content.endswith('whammy'):
await message.channel.send('response {0.author.mention}'.format(message))
client.loop.create_task(change_status())
client.run(token)
BTW, pls don't post your token

Categories

Resources