How to DM a user without them doing anything in the server - python

I'm creating a simple DM part of a bot and I've tried this method but it keeps giving me an error.
Code:
import discord
from discord.ext import commands
TOKEN = "Token Here"
#client.event
async def on_message(message):
if message.author == client.user:
return
me = await client.get_user_info('Snowflake ID Here')
await client.send_message(me, "Message Here")
client.run(TOKEN)
It keeps giving me this error:
NameError: name 'client' is not defined
This method seems like the user needs to send a message but is there a way to do it without the user needing to send a message.

import discord
from discord.ext import commands
client = disord.Client(intents=discord.Intents.all()) # define client
# could also be commands.Bot()
#client.event
async def on_message(message):
if message.author == client.user:
return
me = client.get_user(1234) # user id, must be int type
await me.send("Message Here") # client.send(me, "message here") doesnt work in discord.py version 1.x
client.run("TOKEN")

Client Example
import discord
class MyClient(discord.Client): # defineding client
async def on_ready(self): # event
print('Logged on as', self.user)
async def on_message(self, message): # event
if message.author == self.user:
return
you = self.get_user(1234)
await you.create_dm() # go to DM
await you.send("Message Here")
client = MyClient()
client.run('token')
Bot Example
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>') # defineding client
#bot.event
async def on_ready():
print('Logged on as', bot.user)
#bot.event
async def on_message(message):
if message.author == bot.user:
return
you = bot.get_user(1234)
await you.create_dm() # go to DM
await you.send("Message Here")
bot.run('token')

Related

Discord Bot not responding to commands... (Using Pycord)

Im trying to make a discord bot, and I want its first command to be pretty simple, I just want it to respond "pong!" when someone types "!ping" but when I try to run the command, nothing happens.. I've tried using other commands too but they all result in errors.. I'm a beginner to using Python, so please, can someone tell me what's wrong with my code, and how I can fix it?
In short, my bot doesn't respond back when I type the command I made for it to do so.
import discord
import os
from discord.ext import commands
from discord.ext.commands import Bot
case_insensitive=True
client = discord.Client()
bot = commands.Bot(
command_prefix="!",
intents=discord.Intents(members=True, messages=True, guilds=True)
)
#client.event
async def on_ready():
print('logged in as {0.user}!'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
#bot.command(name="ping", description= "Find out!")
async def ping(ctx):
await ctx.send("Pong!")
client.run(os.getenv('TOKEN'))
Instead of #bot.command you should use #client.command.
Also no need for the from discord.ext.commands import Bot import
So your new code would be
import discord
import os
from discord.ext import commands
case_insensitive=True
client = discord.Client()
bot = commands.Bot(
command_prefix="!",
intents=discord.Intents(members=True, messages=True, guilds=True)
)
#client.event
async def on_ready():
print('logged in as {0.user}!'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
#client.command(name="ping", description= "Find out!")
async def ping(ctx):
await ctx.send("Pong!")
client.run(os.getenv('TOKEN'))
You could just do inside on_message code block
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!ping'):
await message.channel.send('Pong!')
client.run('your token here')

how to i import/use ctx for a python discord bot?

im making a python discord bot in replit and i cant get ctx to work
i tried import ctx and i just get an error message like AttributeError: module 'ctx' has no attribute 'message' heres my code:
import discord
import ctx
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith(""):
print(message.content)
guild = ctx.message.guild
await guild.create_text_channel('cool-channel')
client.run(os.getenv('TOKEN'))
my_secret = os.environ['TOKEN']
If you want to use the ctx parameter, you're supposed to use the commands extension for discord.py. In the on_message event you can use the message parameter "as ctx parameter".
#client.event
async def on_message(message):
if message.author != client.user:
if message.content.startswith(""):
print(message.content)
guild = message.guild
await guild.create_text_channel('cool-channel')
You should not need to use the ctx library to access the message variable's guild property. Try the following:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith(""):
print(message.content)
guild = message.guild
await guild.create_text_channel('cool-channel')

Read RPG bot in discord using Python bot

Am trying to make simple python bot to read RPG bot and when there is group event it would send text to call everyone to come. Am using Replit so I would say the latest python 3.8.2
import requests
import discord
import time
client = discord.Client()
async def on_ready():
print('Logged in As {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
if message.content.startswith('Event'):
time.sleep(2)
await message.channel.send("Event Starting #everyone")
if any(word in msg for word in ('event')):
time.sleep(2)
await message.channel.send("#everyone Event time")
client.run(os.environ['token'])
Try to use discord rewrite if you are not use that https://github.com/Rapptz/discord.py
Small example with using your code:
import discord
from discord.ext import commands
import time
import os
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
bot.remove_command("help")
token = "token here"
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.event
async def on_message(msg):
await bot.process_commands(msg)
if msg.author == bot.user or msg.author.bot:
return
elif "event" in msg.content.lower(): #here we are lower all message content and try to finding "event" word in message.
time.sleep(2)
await msg.channel.send("Event Starting #everyone")
return
#if you want to use this as bot command, not as default text.
#bot.command(name="event")
async def event(msg):
time.sleep(2)
await msg.channel.send("Event Starting #everyone")
return
bot.run(token)

Discord.py how to add a role to a member

I have this code witch checks when someone wrights "send #user to court" and then gets the mentioned person id and wrights "sending to court" but im trying too make it add the role "court" but it doesent work heres the code:
import discord
from discord.ext import commands
import ctx
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
if re.search("^send.*court$", messageContent):
user_id = message.mentions[0].id
await message.channel.send('sending to court!')
role = discord.utils.get(server.roles, name="court")
await client.add_roles(user_id, role)
client = MyClient()
client.run('TOKEN')
You can also use message.content directly in len() and re.search() (if you don't need it later again)
For re.search() you have to import re
You haven't got a variable server so you can't use it in server.roles as python can't get the server just from nothing
(Main Problem) It's not client.add_roles, it's member.add_roles where you have to use a Member object
Revised:
import discord
from discord.ext import commands
import ctx
import re
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
if len(message.content) > 0:
if re.search("^send.*court$", message.content):
user = message.mentions[0]
await message.channel.send('sending to court!')
role = discord.utils.get(message.guild.roles, name="court")
await user.add_roles(role)
client = MyClient()
client.run('TOKEN')

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")

Categories

Resources