Skip to content

Instantly share code, notes, and snippets.

@AndreMor8
Last active June 1, 2023 03:10
Show Gist options
  • Save AndreMor8/a78948db150e0bc515ad1f2252cdfab3 to your computer and use it in GitHub Desktop.
Save AndreMor8/a78948db150e0bc515ad1f2252cdfab3 to your computer and use it in GitHub Desktop.
Twitter notification to Discord
// .env -> process.env
require("dotenv").config();
// I will use axios as it comes with the next package as well.
const axios = require("axios");
// Our function for the bot to send a message
function createMessage(channelID, content) {
//You need the token from your Discord bot.
return axios.post(`https://discord.com/api/v8/channels/${channelID}/messages`, content, {
headers: {
Authorization: `Bot ${process.env.DISCORD_TOKEN}`,
'Content-Type': 'application/json'
}
});
}
// This library includes all the methods of the Twitter API v2, which includes receiving tweet notifications depending on the rules.
const { FilteredStream } = require("twitv2-stream");
// Create a client. You need the bearer token from Twitter Developers.
const twitter = new FilteredStream({ token: process.env.TBEARER });
// We add a rule. In this case, receive notifications that come from X ID.
// More info here: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule
twitter.addRule([
{ "value": "from:1220891440756248576", "tag": "andremor" }
]);
// Upon receiving the tweet, log the tweet and send it via our function.
twitter.on("tweet", (tweet) => {
console.log(tweet);
createMessage("663909563929722880", { content: `AndreMor posted!\n\nhttps://twitter.com/AndreMor8/status/${tweet.data.id}` })
});
//Other events
twitter.on("heartbeat", () => {
console.log("Heartbeat received!");
})
twitter.on("connected", () => {
console.log("Posting tweets!");
});
twitter.on("api-errors", (err) => {
console.error(err);
});
twitter.on("stream-error", (err) => {
console.error(err);
})
// Connect to the API.
twitter.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment