I am currently working on a desktop application and I want to get messages sent from Discord to this application. How should I do this?
I have used POST requests and webhooks to send messages TO Discord, but I have never taken messages from a channel and sent them somewhere else.
I know I can do something using on_message like this:
#bot.event
async def on_message(message):
message_content = message.content
## send message_content to external application
I just am confused on what to use/how to send the messages to the application itself. Keep in mind that this I'm making in Python 3.6.6
Related
So I want to know if it is possible, that a bot gets the content sent to it in a dm and send that in a specifyed channel on a server.
So basically you dm the bot the word "test" and the bots sends the word in a channel of a server
Yes, it is possible for a bot to receive a direct message and then repost the message in a specified channel on a server. This can be done using the Discord API.
You can do the following:
Create a Discord bot and add it to your server. You can do this using the Discord developer portal.
Use the Discord API to listen for messages sent to the bot in a DM. You can do this using the message event and the DMChannel class in the Discord API.
When the bot receives a DM, use the Discord API to repost the message in the specified channel on the server. You can do this using the send method of the TextChannel class in the Discord API.
Yes, this is possible:
First, we use the on_message() event to detect when a message is sent.
We then check if the message is sent in a DM.
If so, we will send a message to a specific channel.
Here is one way you can implement it:
# import ...
bot = discord.Bot(...)
#bot.event
async def on_message(message):
# check if it's
if isinstance(message.channel, discord.DMChannel):
# get the channel from ID
channel = client.get_channel(CHANNEL_ID) # put channel ID here
await channel.send("test") # whatever you want to send
#bot.event:
async on_message(message):
if message.DMChannel:
# define channel and send message to channel.
You can also refer to DOCS.
I have for the moment a code that sends a message but only for my own discord server as a bot.
What I would like it's automated sending message to others servers to simulate an activity as if it were my main account
def sendMessage(ch, ms):
client = discord.Client()
#client.event
async def on_ready():
channel = client.get_channel(ch)
await channel.send(ms)
return ""
client.run('token')
How to make the sendMessage code sending a message using my main account?
Please, do not do this.
Like Silvio said, if you find a way to send messages as a user through code and you are caught then you might get banned. Don't say we didn't warn you!
This question has been asked before (How to get the message content printed out of a discord webook! in python) but has been closed. So I hope I'm within my rights to open a new question on the topic?
The following szenario:
We use the discord notification service from gitlab (https://docs.gitlab.com/ee/user/project/integrations/discord_notifications.html) to post new issue/push to master-notifications to one of our discord channels using discord.py. This channel is also linked to another chat via bot so that both chats always have the same content. This is working so far.
When I now try to get print(message.content) it's empty concerning messages from gitlab, even though it displays a message in discord. The basic structure looks like this:
import discord
import re
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
# modifying and preparing messages for sync with second chat
# I removed this because it shouldn't have anything to do with the problem
# trying to find the message content
print(message.author)
print(message.content)
print(message)
print('----------')
# write messages into database
client = MyClient()
client.run('TOKEN')
print(message) returns something like <Message id=1234 channel=<TextChannel id=5678 name='some-name' position=1 nsfw=False news=False category_id=9012> type=<MessageType.default: 0> author=<User id=3456 name='Bot Name' discriminator='0000' bot=True> flags=<MessageFlags value=0>>
I did read large parts of the API reference (https://discordpy.readthedocs.io/en/latest/api.html) but could not find anything. Though I could not make heads or tails of the webhook part (https://discordpy.readthedocs.io/en/latest/api.html#webhook-support).
Any ideas how to obtain the message content from a message that comes from a webhook? It's gotta be somewhere ...
Thank you in advance,
Christian
Update 2020-10-23
I have tried getting more details about the information send from GitLab to Discord by creating an event listener via https://pipedream.com/ but it did not record any events (set to "new issue", created several), while a listener for discord (on new messages) worked fine.
The setup is as follows:
Create a Webhook in Discord (https://discord.com/api/webhooks/[id]/[token])
Feed said Webhook into the settings in GitLab and choose from a multitude of triggers.
I do not know how I could get the header-data GitLab sends to Discord under these circumstances. I also checked the Webhook provided by Discord using Postman - it merely returns the Bots basic stats.
GitLab sends the message content as embed (https://discordpy.readthedocs.io/en/latest/api.html#embed)
In my case the information I was looking for was right before my eyes. You can access it, using message.embeds[0].description.
I could not make heads or tails off the API description to embeds, but it seems, I also never tested what it does and then started to go in circles.
I have problem creating simple python script which sends message to default channel when executed from terminal.
import discord
#bot.event
async def on_ready(ctx):
print('Online')
await ctx.send('Message sent!')
bot.run('MYTOKEN')
with this example I keep getting "ctx" is not defined
The issue here is that the on_ready event should not receive any parameters. See the Minimal Bot documentation here and the on_ready documentation in the Event Reference here. If you want to send a message when the bot connects. You must first get the channel object and then use the send method. You can find an example of getting a channel and sending a message in the FAQ section of the docs here
I am designing an app where I can send notification to my discord channel when something happen with my python code (e.g new user signup on my website). It will be a one way communication as only python app will send message to discord channel.
Here is what I have tried.
import os
import discord
import asyncio
TOKEN = ""
GUILD = ""
def sendMessage(message):
client = discord.Client()
#client.event
async def on_ready():
channel = client.get_channel(706554288985473048)
await channel.send(message)
print("done")
return ""
client.run(TOKEN)
print("can you see me?")
if __name__ == '__main__':
sendMessage("abc")
sendMessage("def")
The issue is only first message is being sent (i-e abc) and then aysn function is blocking the second call (def).
I don't need to listen to discord events and I don't need to keep the network communication open. Is there any way where I can just post the text (post method of api like we use normally) to discord server without listening to events?
Thanks.
You can send the message to a Discord webhook.
First, make a webhook in the Discord channel you'd like to send messages to.
Then, use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you.
Finally, use the discord.Webhook.send method to send a message using the webhook.
If you're using version 2 of discord.py, you can use this snippet:
from discord import SyncWebhook
webhook = SyncWebhook.from_url("url-here")
webhook.send("Hello World")
Otherwise, you can make use of the requests module:
import requests
from discord import Webhook, RequestsWebhookAdapter
webhook = Webhook.from_url("url-here", adapter=RequestsWebhookAdapter())
webhook.send("Hello World")
I have found it. "Webhook" is the answer. Instead of using discord.py, just create a webhook for your channle and then just post the data to that endpoint.
import requests
#Webhook of my channel. Click on edit channel --> Webhooks --> Creates webhook
mUrl = "https://discord.com/api/webhooks/729017161942******/-CC0BNUXXyrSLF1UxjHMwuHA141wG-FjyOSDq2Lgt*******************"
data = {"content": 'abc'}
response = requests.post(mUrl, json=data)
print(response.status_code)
print(response.content)
This might be one of the best approaches as it saves the addition of more python packages(one mentioned by #john), but I believe there is a more robust and easy solution for this scenario, as you can add images, make tables and make those notifications look more expressive.
A python library designed for the explicit purpose of sending a message to the discord server. A simple example from the PyPI page would be:
from discord_webhook import DiscordWebhook
webhook = DiscordWebhook(url='your webhook url', content='Webhook Message')
response = webhook.execute()
more examples follow on the page.
This is how the sent notification/message would look like
Discord notification with table