I'd like to send a bot message in a discord channel via google apps script when a certain event is triggered, but I don't know where to start. Is this even possible? If not, is there a way to do it via github?
EDIT: I have figured out how to get the OAuth tokens, now how do I make the bot send a message?
I know that there's pretty much no chance that the OP still needs this answer, but I'm putting it up here so that others who google this question will be able to find the answer
var webhooks = {
test: "Obtain a webhook for the channel you'd like and put it here."
};
function sendMessage(message, channel)
{
if(webhooks.hasOwnProperty(channel))
var url = webhooks[channel];
else {
Logger.log("Error Sending Message to Channel " + channel);
return "NoStoredWebhookException";
}
var payload = JSON.stringify({content: message});
var params = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText());
}
// to call and send a message
sendMessage("Hi!", "test");
This is what I typically use for sending messages. Unfortunately, there's no way to receive triggers from the webhooks to my knowledge.
Note: The above answer references discord.js, which is not compatible with Google Apps Script
To start with, here is a documentation from discord.js.
To let your apps script communicate with discord, you can check the External APIs
Google Apps Script can interact with APIs from all over the web. This
guide shows how to work with different types of APIs in your scripts.
Examples are available in the provided documentations.
See these useful links for further details.
Website (source)
Documentation
Discord.js server
Discord API server
GitHub
NPM
Related libraries (see also discord-rpc)
Super easy. Just go to your Discord channel, choose "Edit Channel" > "Webhooks". You name the bot and set its profile picture. It will give you a webhook URL that already contains the authorization token.
Then you just POST to that public URL. TADA, a message will appear in the given channel, sent by the bot.
function postMessageToDiscord(message) {
message = message || "Hello World!";
var discordUrl = 'https://discordapp.com/api/webhooks/labnol/123';
var payload = JSON.stringify({content: message});
var params = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
}
Source: https://ctrlq.org/code/20563-post-message-to-discord-webhooks
For anyone still looking and not having luck with previous answers, like me:
After making my message_string, this snippet successfully sent to my desired channel's webhook:
// Send the message to the Discord channel webhook.
let options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
},
"payload": JSON.stringify({
"content": message_string
})
};
Logger.log(options, null, 2);
UrlFetchApp.fetch("your_webhook_url_here", options);
I can't make a comment yet, but if you are having issues with one of the above answers - try changing the content type from:'Content-Type':"application/x-www-form-urlencoded" to 'Content-Type':"application/json".
Related
Currently, I know how to send a normal message with JS, as the code shows below. But how could I turn it into an embed? (front-end)
const url = '*********************************************************************************'
const msg = {
"content": `this is a discord webhook message`
}
fetch(url, {
"method": "POST",
"headers": { "content-type": "application/json" },
"body": JSON.stringify(msg)
})
I tried searching, but found nothing in match to my inquiry.
You should read the documentation!
I assume, because of your content, that you are executing a webhook. So let's look at the documentation as to what may be provided for executing a webhook (creating a normal message is the same in this scenario): https://discord.com/developers/docs/resources/webhook#execute-webhook
The table has content in it just like you have as well as what you're after: embeds. It says it's an array of up to 10 embed objects. All you do now is visit the hyperlink to find out what you're able to use in an embed object and pass it as an array.
For example, { description: "test" } is a valid embed object. Put that in an array and place it alongside your content (or omit it) with the key embeds.
I'm trying to assign a discord role to a member using OAuth2 on my website. They sign in, I get the access token (which works with other requests), and then send the request below with every header and variable being correct.
factionRoleMapping = { OG: "929218237030354994" };
const newRoles = [...currentRoles, factionRoleMapping[faction]];
var rolesInfoFetch = await fetch(
`https://discord.com/api/v9/guilds/${config.GUILD_ID}/members/${req.body.uid}`,
{
method: "PUT",
headers: { Authorization: req.headers.authorization },
body: {
roles: newRoles,
},
}
);
I read the docs and it said that I would get a 204 No Content if the user was already in the discord guild, which I'm guessing should be okay. But I keep getting 401 Unauthorized.
The current permissions are "guilds", "guilds.join", "guilds.members.read", and "identify".
I'm not even sure if this is possible the way I'm doing it, but any help is appreciated!
Authorization header should be in format of Bot your.bot.token
also your question is unrelated to discord.js
Like the title describes, i can't seem to figure out how to upload a local image and have it posted as a message in slack
Currently i am able to post text messages to slack without issue using the webhook url and axios post seen here:
const res = await axios.post(url, {
text: 'Screenshot',
channel: channelid
}, {
headers: {
authorization: `Bearer ${token}`
}
});
Heres the part of the script that isnt working:
try {
const result = await client.files.upload({
channels: channelid,
initial_comment: "this is the image",
file: fs.createReadStream(fileName)
});
console.log(result);
} catch (error) {
console.error(error);
}
I dont understand how the channelid works in one and not the other.
Calling a method with an xoxb or xoxp token is different than posting a message with a webhook. When you create the webhook on the Slack Developer settings site, you are asked to choose a channel. The webhook will be able to post into that channel without your app being a channel member. When using the xoxb token your bot needs to be a member of the channel that's being passed in the API call. If it's not a member you can expect a channel_not_found or not_in_channel error.
You should add the bot to the channel using
/invite #bot-name
Im trying to make a discord bot where if you type -cr into the chat, it takes the Arguments of the user (Being the Clash Royale Player's player tag) and would then use the package node-fetch to receive data with my specified endpoint. I am constantly running into the error of { reason: 'accessDenied', message: 'Invalid authorization' }. Im rather new to this stuff, especially API's, but im hoping to access certain data which I can decide later on (Which I know how to do). My code is :
const fetch = require('node-fetch')
module.exports = {
name: 'clash',
aliases: ['cr', 'clashroyale'],
category: 'This',
utilisation: '{prefix}clash',
async execute(client, message) {
var msgArgs = message.content.slice(this.name.length + 1)
var endpoint = `/players/${msgArgs}`
var url = `https://api.clashroyale.com/v1`
var token = `hidingmytoken`
fetch(url + endpoint, {
method: 'POST',
headers: {
"Authorization": token
}
}).then(data => data.json()).then(json => {
console.log(json)
})
},
};
The message parts with msgArgs and discord sides all work but fetching that clash Royale API is a big hurdle for me. The API for Clash Royale can be found here https://developer.clashroyale.com/#/documentation and Im just generally stuck on this whole concept. Im using version 2.6.6 of node-fetch so I can use the require() method which should work if that does matter. In general, how can I pass my token properly to receive that API data?
Since the Clash Royale API uses bearer authentication, you need to specify that it will be a bearer token.
headers: {
'Authorization': `Bearer ${token}`
}
I've implemented the following functionality. The code is written in GO but you can copy the logic and translate into your language.
The library have the following functionality:
Login
Token generation
Token list
Token delete
https://github.com/alessiosavi/GoClashRoyale/blob/master/api/auth.go
this is my first time posting a question to stack overflow since I have an issue I cant get past.
What I am trying to do:
I am trying to extract data of my car from the "Mercedes me" platform. It's a pure hobby project.
"Mercedes me" has an API with oAuth2 verification.
I am trying to realize this in Google Sheets since I want to do calculations with the data retrieved.
Hence I started coding in Apps Script.
I am able to exchange an Authentification Code with a Token and then get data from the platform using the following code:
var options = {
headers : { Authorization: 'Basic '+ Utilities.base64Encode('Client ID:Client Secret')},
method : 'post',
'content-type' : 'application/x-www-form-urlencoded',
muteHttpExceptions : false,
}
var authorization_code = 'TGVWD9pNif1wuDBYa6fFPn4QHNW9h6_f2-kxL34V'
var authUrl = 'https://id.mercedes-benz.com/as/token.oauth2?grant_type=authorization_code&code='+authorization_code+'&redirect_uri=https://localhost/';
var response = UrlFetchApp.fetch(authUrl, options);
var data = JSON.parse(response);
var token = data.access_token
'Logger.log(token);'
var options = {
headers : { Authorization: `Bearer ${token}`},
accept : 'application/json'
}
var response = UrlFetchApp.fetch('https://api.mercedes-benz.com/vehicledata/v2/vehicles/<vehicle identification number>/resources/', options);
'var jsonObject = JSON.parse(response.getContentText()); '
'var jsonObject = JSON.stringify(response);'
Logger.log(response);
So this is not the issue. The issue is that currently I need to manually insert the Authorization Code (as you can see in the code snippet above) which will then be exchanged with the Token by my script. The goal would be to generate the Authorization Code automatically.
I have created an authorization URL which will give me the Authorization Code when entered and opened in the Browser.
However, when I try to achieve the same in Apps Script via UrlFetchApp it will send me back some unusable html code instead of an Authorization Code.
function Authentification() {
var url = 'https://id.mercedes-benz.com/as/authorization.oauth2?response_type=code&client_id=a9f67f5f-cb2b-413b-9ea5-78df02b668a1&redirect_uri=https://localhost/&scope=mb:vehicle:mbdata:payasyoudrive&state=1000';
var options = {
muteHttpExceptions : false, //theoretisch nicht notwendig
followRedirects : true, //theoretisch nicht notwendig
method : 'get', //theoretisch nicht notwendig
}
var response = UrlFetchApp.fetch(url, options);
var json = response.getHeaders;
var data = JSON.stringify(json);
Logger.log(response)
}
Result is some html like this:
<!DOCTYPE html><html lang=en xmlns=http://www.w3.org/1999/xhtml><head><meta charset=utf-8><m
But what I am trying is to get a redirect Url like this (including the Authorization Code):
https://localhost/?code=DXPzKdV58t3rWlpuVmD3XT35BbL__n0auuAxL34V&state=1000
My assumption is, the problem is that when the link is opened by Apps Script's URLFetchApp it is never asked to enter my "Mercedes me" login credentials. Most likely I am not seing a basic OAuth logic here. Would really appreciate your help. Thanks a lot in advance.
Best Regards,
Chris
The solution came to my mind in my sleep :-D
I deployed the whole thing as a webapp and used the webapp-link as the redirect uri.
After this I was able to extract the authorization code from the url with the following code:
function doGet(e) {
var param = e.queryString;
param = e.parameter;
var code = param.code;