discord.py - Send messages though console - python

ok, I wanted so I could send messages in an specific server and channel form the console. I seen on other post how to send messages on specific servers and channels but theyr from the discord app and not console. Can someone help me?
I wanted so I type msg [server-id-here] [channel-name] [message] for example
msg 493121776402825219 general hello
Code I have but it has errors
#bot.event
async def on_ready(ch, *, msg):
while msg:
channel = bot.get_channel(ch)
msg=input("Mensagem: ")
if channel:
await bot.send_message(channel, msg)
else:
await bot.say("I can't find that channel")
Error that outputs
TypeError: on_message() missing 1 required positional argument: 'ch'

I don't this this is actually possible, however you can implement a new command to do it, heres the one I used for welcomer
#bot.command(description="Echos, developers only", pass_context=True)
async def echo(ctx, echowords:str):
if ctx.message.author.id in []: #put in id's in a list or replace it with one string
await bot.say(echowords)
else:
await bot.say("Bot developers only :<")
This makes the bot repeat what you said where you said it, but if you want to send messages to a specific channel by ID you can do this
#bot.command(description="Echos, developers only", pass_context=True)
async def echo(ctx, id, echowords:str):
if ctx.message.author.id in []: #put in id's in a list or replace it with one string
sendchannel = bot.get_channel(id)
await bot.send_message(sendchannel, echowords)
else:
await bot.say("Bot developers only :<")

Use the say command.
#bot.command()
async def say(ctx, *,message):
if not ctx.author.bot:
else:
pass

Related

is there a way to send a message after a message has been deleted?

So, when a user sends a message I want my bot to send a message to that channel with an emoji
so far I've been able to send it to a specific channel, but after that I haven't been able to send a message to any channel that a message was deleted in.
maybe I just don't know the attributes.
thanks for all the help in advance!
#bot.event
async def on_message_delete(ctx):
if ctx.author.id != 835676293625282601:
author = ctx.message.author
del_msg = await channel.send(":eyes:")
await author.send(del_msg)
await asynciaito.sleep(10)
await del_msg.delete()
Events never take ctx as an argument, if you take a look at the docs you can see that on_message_delete takes message as the only argument
#bot.event
async def on_message_delete(message):
if message.author.id != 835676293625282601:
author = message.author
del_msg = await message.channel.send(":eyes:")
await author.send(del_msg)
await asynciaito.sleep(10)
await del_msg.delete()
Also you don't have to learn all the attributes from all the discord objects, just read the documentation

I'm trying to create a discord bot that will ping a role, with a sponsor and message, but It includes the entire message, what can I do?

So I'm trying to make a discord bot with python, and I would like it to ping a certain role, adding parts of your message into specific places. Such as: #role, Sponsor: #person, Message: message.
This is my code;
if message.content[11:] != message.content:
if message.content[10:] != "#Johnny Wobble#1085":
print("confirmed stage 2")
responses = [
"<#&820375570307088404>",
f"Sponser: {message.content[10:]}",
f"Message: {message.content[11:]}",
]
await message.delete()
await message.channel.send(responses)
else:
print("confirmed stage 3")
await client.send_message(message.channel, f"Ah, I see you {message.author.mention}, trying to turn me agai"
f"nst my master eh? Well I say no! I cannot believe you would think that I would ever do that to the all-po"
f"werful Max (Gordon)!")
I tried this code but it just ends up repeating the entire message.
For example: -gw #person pls work
Then it returns '#role' 'Sponsor: #person pls work' 'Message: #person pls work'
Do I have some problems in my code?
I would suggest using the commands extension rather than using an on_message event. If you're already doing that and I misread your question, please view the next section of this answer.
from discord.ext import commands # unsure if importing is necessary, usually used for cogs
# ...
# set up code with client and on_ready and what not
# ...
#client.command()
async def sponsor(ctx, role: discord.Role, *, message="Sponsor message"):
# get the role if given is valid, message is 'Sponsor message' if nothing is given
await ctx.send(f"""
{role.mention}
Sponsor: {ctx.author.mention}
Message: {message}
""")
# role.mention : mentions the given role
# sponsor : mentions the person who originally invoked the command
Assuming that you are using the commands extension already, you may use client.wait_for. This is used if you want your bot to listen to the channel for a specific message under a command.
#client.command()
async def sponsor(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send("Send the thing:")
response = await client.wait_for('message', check=check)
# Two different ways you may want to split your message:
# --- The first way to do it would be to split at a certain keyword, for example 'msg' --- #
role, message = response.content.split('msg:', 1)
# --- The other way would be to split it from the first space --- #
role, message = response.content.split(' ', 1)
# sending the message here
await ctx.send(f"""
{role}
Sponsor: {ctx.author.mention}
Message: {message}
""")
Working Method 1
Working Method 2
References:
SO: Split a string only by first space in python
SO: Discord.py-rewrite wait_for() how do i use?
SO: Discord.py wait_for()
Docs: wait_for(event, *, check=None, timeout=None)

how to allow specific messages discord bot python in specific channels

So I want to make my bot allow specific messages, like "/verify" in a specifc channel, if someone sent a message other than "verify" the bot should delete the message, however only in a specific channel, I'm new to all of that but I made this code and it's not working
async def verify(ctx):
user = ctx.message.author
role = 'Member' #change the role here
try:
await user.add_roles(discord.utils.get(user.guild.roles, name=role))
await ctx.send('Welcome to our server! :white_check_mark:', delete_after=1)
except Exception as e:
await ctx.send('Cannot assign role. Error: ' + str(e))
if not msg.content == '/verify':
await client.delete_message(msg)
await ctx.message.delete()
any help would be much appreciated.
You can just write a simple check right at the beginning of the function.
For example,
#bot.command()
async def verify(ctx):
if ctx.channel.name != "verify":
return
# rest of the code
Also, you have not defined msg in your code. So that'll also raise an error
You have to specify what exactly your "msg" is that you want to delete.
So instead of msg.delete it should be enough to instead write:
if ctx.message.content == "verify":
await ctx.message.delete
Because the ctx/context is where you get the information about what kind of message it is, which channel it was posted in and so on.

How to receive and send message to specific channel in Discord.py?

Yesterday I was working on something simple where a bot on command of !name Barty would print back Hello Barty
#bot.command()
async def name(ctx, args):
await ctx.send("hello {}".format(args)
However the problem I am facing at this moment is that the bot would response to any channel where I do use the !name XXXX and what I am trying to do is that I want only to react to given specific channel in discord.
I tried to do:
#bot.event
async def on_message(message):
if message.channel.id == 1234567:
#bot.command()
async def name(ctx, args):
await ctx.send("hello {}".format(args)
but that was completely not working and I am out of ideas and here I am.
How can I send command to a given specific channel and get back response from there?
Move the define code out of the IF statement:
#bot.command()
async def name(ctx, args):
await ctx.send("hello {}".format(args)
When you've done that, you should be able to do;
if (message.channel.id == 'channel id'):
await message.channel.send('message goes here')
else:
# handle your else here, such as null, or log it to ur terminal
Could also check out the docs: https://discordpy.readthedocs.io
Once you make the command, make the IF statement inside of that.
message.channel.id now needs to be an integer, not a string so you don't need to use ''
if (message.channel.id == 1234567):
await message.channel.send('message goes here')
else:
# handle your else here, such as null, or log in to ur terminal

Python - DM a User Discord Bot

I'm working on a User Discord Bot in Python .If the bot owner types !DM #user then the bot will DM the user that was mentioned by the owner.
#client.event
async def on_message(message):
if message.content.startswith('!DM'):
msg = 'This Message is send in DM'
await client.send_message(message.author, msg)
The easiest way to do this is with the discord.ext.commands extension. Here we use a converter to get the target user, and a keyword-only argument as an optional message to send them:
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await bot.send_message(user, message)
bot.run("TOKEN")
For the newer 1.0+ versions of discord.py, you should use send instead of send_message
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)
bot.run("TOKEN")
Since the big migration to v1.0, send_message no longer exists.
Instead, they've migrated to .send() on each respective endpoint (members, guilds etc).
An example for v1.0 would be:
async def on_message(self, message):
if message.content == '!verify':
await message.author.send("Your message goes here")
Which would DM the sender of !verify. Like wise, you could do:
for guild in client.guilds:
for channel in guild.channels:
channel.send("Hey yall!")
If you wanted to send a "hi yall" message to all your servers and all the channels that the bot is in.
Since it might not have been entirely clear (judging by a comment), the tricky part might get the users identity handle from the client/session. If you need to send a message to a user that hasn't sent a message, and there for is outside of the on_message event. You will have to either:
Loop through your channels and grab the handle based on some criteria
Store user handles/entities and access them with a internal identifier
But the only way to send to a user, is through the client identity handle which, in on_message resides in message.author, or in a channel that's in guild.channels[index].members[index]. To better understand this, i recommend reading the official docs on how to send a DM?.
I used this command in the past and it in my opinion it works the best for me:
#bot.command(pass_context=True)
async def mall(ctx, *, message):
await ctx.message.delete()
for user in ctx.guild.members:
try:
await user.send(message)
print(f"Successfully DMed users!")
except:
print(f"Unsuccessfully DMed users, try again later.")
#bot.command()
async def dm(ctx, user: discord.User, *, message=None):
if message == None:
message = "Hi!"
embed = make_embed(title=f"Sent by {user}", desc=message)
await user.send(embed=embed)
await ctx.send("Message sent!")```
I have noticed that each code I put into my code lines they don't work completely, so I added my own bit to them and bam it works! When adding this to your bot's code, don't forget to add the bot's name where it says bot name here. It will only DM the person who sent it, but you can change what it says each day for a surprise for everyone that used the command. It works every time for me.
#client.command()
async def botdm(ctx):
await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')

Categories

Resources