discord.py send pm on member join - python-3.x

I'm trying to write a bot that sends a user a pm when he joins the server.
I searched and I found that to d this you need to have intents enabled, but when I enable them it gives me an error "RuntimeError: Event loop is closed". I can't figure out what exactly not working, I've seen somewhere that regenerate the bot token helps but it didn't help for me.
this is the code:
import discord
from discord.ext import commands
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member}"
await member.send(welcome_msg)
bot.run(TOKEN)

I see that you are trying to DM the user as soon as they join a server, you should did {member} and the argument "member" is just a guild version of The user, and to display the name with member.name there for it will show the Member's name on the message.
Here is your Fixed Code:
import discord
from discord.ext import commands, tasks # add tasks if you're going to do tasks.
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member.name}" # You don't need to define the message.
await member.send(welcome_msg) # You can do await member.send("message") instead of defining it.
bot.run(TOKEN)
Hope this helped. Have a nice day!

Related

Discord.py not responding to #client.event commands

I am not getting a "ping" response with this code. It was working before, but I am not sure what changed. There are no errors on my end, just no response.
Any feedback is appreciated.
import os
import random
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
PREFIX = os.getenv("PREFIX")
TOKEN = os.getenv("TOKEN")
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
#bot.event # ping-with-latency
async def on_message(message):
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')
#bot.event
async def on_ready(): # display if online/ready
print("Bot is ready and logged in as {0.user}!".format(bot))
# run bot on server
bot.run(TOKEN)
I have checked all permissions and privileged gateway intents. I know I could be using client.command, but that also doesnt work.
You're defining two different callbacks for these events - this is probably the problem. Just put the author check in the main on_message.
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')

How do i make a discord bot receive text after a command

I want to become a fake discord bot, so i can use: !!send or something like that.
I have the token ready and i tried some repl.it templates but i have no idea of what to do.
here is the code i tried:
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
os.environ["TOKEN"] = "no-token-for-you-to-see-here"
#^ basic imports for other features of discord.py and python ^
client = discord.Client()
client = commands.Bot(command_prefix = '!!') #put your own prefix here
#client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
#client.command(pass_context=True)
async def send(ctx,*,message):
await client.say(message)
client.run(os.getenv("TOKEN")) #get your bot token and create a key named `TOKEN` to the secrets panel then paste your bot token as the value.
#to keep your bot from shutting down use https://uptimerobot.com then create a https:// monitor and put the link to the website that appewars when you run this repl in the monitor and it will keep your bot alive by pinging the flask server
#enjoy!
It was online, but the command didn't work.
The command send should be
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
Also, you're defining two client(s). You need only one.
client = commands.Bot(command_prefix = '!!')
You're also importing some useless modules that you don't need right now.
Your final code should look like this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!!")
#client.event
async def on_ready():
print("The bot is online")
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
client.run("token-of-the-bot")
Please tell me if it works or not. Have a great day :)

I got an error on programming a discord bot

I was programing a python discord bot. I got this error:
Code:
# jokeybotmain.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('ODg0NjkxODkzNTk2ODU2MzQw.YTcLiA.pKu1RIyV2HOTFhLOWQX0ryliyco')
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
Error
Your problem is that you put the token (copied from discord developer portal) as a parameter for os.getenv.
You can instead remove the part about dotenv and make your bot work, like this:
import discord
TOKEN = "Your token here" # Remember to delete it before sending your code
# Use Bot instead of Client
# https://stackoverflow.com/questions/51234778/what-are-the-differences-between-bot-and-client
bot = discord.Bot(prefixes=['!'], intents=discord.Intents.all())
Bot.run(TOKEN)
import discord
from discord.ext import commands
TOKEN = "YOUR_TOKEN"
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)

Why does discord.py discord.ext.commands not work?

I tried making a bot with discord.py
bot = commands.Bot(command_prefix='$', description="This is a test bot")
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
#bot.command(name='ping')
async def ping(ctx):
await ctx.send("pong")
It doesn't send messages when i tell it to. I am using discord.py 1.7.3 with python 3.9.4
The console says it connected but it doesn't do anything other than appear online.
i told it
$ping
full code:
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
# load token (dont share pls)
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
# Is this better?
bot = commands.Bot(command_prefix='$', description="This is a test bot")
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
# commands here
#bot.command(name='ping')
async def ping(ctx):
await ctx.send("pong")
#bot.command()
async def test(ctx, *args):
await ctx.send('{} arguments: {}'.format(len(args), ', '.join(args)))
client.run(TOKEN)
you cant run both discord.Client and commands.Bot
since Bot is the same as Client, with some extra functionality, you should use Bot
remove: client = discord.Client()
change: #client.event to #bot.event and client.run() to bot.run()

I am working on a bot that can mute some with a code, but when i do the command it doesn't work

So I have been working on a discord bot, that mutes people. now I've got everything but, it doesn't say anything, doesn't mute them, please help
import discord
import os
from keep_alive import keep_alive
from discord.ext import commands
bot = commands.Bot(command_prefix="~")
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#bot.command(aliases=['m'])
#commands.has_permissions(kick_members=True)
async def mute(ctx,member : discord.Member):
muted_role = ctx.guild.get_role=807271372035850320
await member.add_roles(muted_role)
await ctx.send(member.mention + " has been muted")
keep_alive()
client.run(os.getenv('token'))
Since you have
client = discord.Client()
All your commands should begin with
#client.command()
Otherwise change it to:
bot = discord.Bot()
This should work too

Resources