Below is the current code. I'm kinda new to python, but my previous bot with virtually the same code ran perfectly fine, so i don't understand why it's not running. The bot will turn on and show as "online" in Discord, but won't send the message.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
For your code to work you need to add a decorator to every method.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'token'
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
# You forgot decorator here
#client.event
async def on_message(message):
channel = message.channel
content = message.content
user = message.author
userid = message.author.id
if content == "hello":
await client.send_message(channel, "rude response")
client.run(TOKEN)
on_message here is not decorated with #client.event hence you just define a function and never call it. Add the decorator to make a listener out of it
#client.event
async def on_message(message):
...
Related
I'm new to coding discord bots, so this might be some easy fix mistake I made but when a member joins my server, the bot doesn't seem to react, be it to add a role or just send a random message in the console.
I'd also add, I'm using replit to host my bot.
import os
import discord
from discord.ext import commands
from replit import db
client = discord.Client()
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "ping":
await message.channel.send("pong")
#client.event
async def on_member_join(member):
print("A member has joined")
role = discord.utils.get(member.server.roles, id="920344130184437931")
await client.add_roles(member, role)
You need to enable Privileged Gateway Intents in Discord Developer Portal.
When you enable that, you need to type this in your code:
intents = discord.Intents.all()
client = commands.Bot('PREFIX',intents=intents)
#client.event
async def on_ready():
print("I'm in")
....
After that on_member_join event should work
I've just started learn python and my discord bot won't go online. it just said
" Process exit with exit code 0". And there's no error with the code.
here's my code. enter image description here
Add await client.process_commands(ctx) and #client.event don't need parentheses(). Use the code given below:
#client.event
async def on_message(ctx):
if ctx.author == client.user:
return
await client.process_commands(ctx)
Use this entire code if it still not working:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(command_prefix="s!")
#bot.event
async def on_ready():
print("running")
bot.run(discord_token)
#bot.command()
async def on_ready():
print("running")
bot.run(discord_token)
and the output should be running
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(client_prefix="!")
#client.command()
async def on_ready():
print("running")
bot.run(discord_token)
The code you gave is wrong, this is correct:
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!") # you don't need an extra discord.client Bot is enough
token = os.getenv("TOKEN")
#you should not run the program here you should run it at last
#bot.event #no need for brackets
async def on_ready():
print("running")
#bot.event
async def on_message(ctx):
if ctx.author == client.user:
return
#bot.command(name="span",description="YOUR DESCRIPTION HERE") # it is command and not commands
async def span_(ctx,amount:int,*,message):
for i in range(amount):
await ctx.send(message)
bot.run(token) #you should run the bot now only and this will work perfectly!
You can find the the documentation for discord.py here.
Im new to python so I cant see where I have made an error.
import discord
import os
from config import TOKEN
client = discord.Client()
#Sends a message in terminal if it has worked
#client.event
async def on_ready():
print('We have logged in as {0.user}'
.format(client))
#Sends a message if !test is included in a sent message
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!test'):
await message.channel.send('test')
#client.event
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = 'Welcome {0.mention} to {1.name}'.format(member, guild)
await guild.system_channel.send(to_send)
client.run(TOKEN)
I've recently began to learn about Discord Bots and tried to make one myself, I've got some basics working but haven't been able to get a new section of the code working which is supposed to get the current datetime and was wondering what I've done wrong.
Edit: This is currently hosted on Heroku so I have no idea how to check for errors
import discord
from datetime import datetime
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_member_join(member):
print(f'{member.name} has joined the server')
channel = client.guilds[0].get_channel(745404752161931266)
print(channel)
await channel.send(f'{member.name} has joined the server')
#client.event
async def on_member_remove(member):
print(f'{member.name} has left the server')
channel = client.guilds[0].get_channel(745404752161931266)
print(channel)
await channel.send(f'{member.name} has left the server')
#client.event
async def on_message(message):
channel = client.guilds[0].get_channel(765757497155649567)
if message.content.find("!hello") != -1:
await message.channel.send("Hello!")
#client.event
async def on_message(message):
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
if message.content.find("!datetime") != -1:
await message.channel.send("date and time =", dt_string)
client.run('[my_token]')
You can't have more than one the same listener, you have to put your whole code in one
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
# ...
elif message.content.startswith('!datetime'):
# ...
A better alternative to that is using commands.Bot, here's an example:
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(f"Logged in as {bot.user}")
#bot.command()
async def hello(ctx):
await ctx.send('Hello!')
# To invoke: `!hello`
bot.run('token')
This class is a subclass of discord.Client and as a result anything that you can do with a discord.Client you can do with this bot.
But if you really wanna stick with discord.Client you can create custom events with client.dispatch('name of the event', *args) sadly there's no docs about it.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
# Dispatching the custom event
client.dispatch('hello', message)
#client.event
async def on_hello(message):
"""Notice how the event it's called `on_hello` not `hello` and
takes the same arguments that we specified in `client.dispatch`"""
await message.channel.send('Hello!')
Also to check the logs from your heroku app:
heroku logs -a {name of the app}
or
heroku logs -a {name of the app} --tail
I am currently using python to code my first discord bot. While trying to write a command, I saw that I was unable to do this. This code:
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'NzQxMjA2OTQzMDc4ODA5NjEy.Xy0Mwg.Shkr9hHvkn-y4l5ye1yTHYM3rQo'
client = discord.Client()
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
is not outputting anything in the discord application when I type !swear. The bot is online, and working normally for other codes such as:
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
Here is the full code:
import discord
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = (##my token spelled out)
client = discord.Client()
#client.event
async def on_ready():
print('im in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
Does anyone know how I can fix my problem?
Client() and Bot() are two methods to create bot and using both at the same time is wrong.
Using Client() and Bot() you create two bots but they would need client.run(TOKEN) and pp.run(TOKEN) to run together - but it makes problem to start them at the same time and it can make conflict which one should get user message.
Bot() is extended version of Client() so you need only Bot() and use
#pp.event instead of #client.event
pp.run(TOKEN) instead of client.run(TOKEN)
pp.user instead of client.user
EDIT:
And you have to define pp before all functions. Like this
import random
from discord.ext import commands
TOKEN = 'TOKEN'
pp = commands.Bot(command_prefix='!')
#pp.event
async def on_ready():
print('im in as {}'.format(pp.user))
#pp.event
async def on_message(message):
if message.author == pp.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#pp.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
pp.run(TOKEN)