Search code examples
javascripttwitterdiscordbots

Build a Discord bot that Tweets


I've been tasked with creating a bot which can create a tweet when someone posts in a Discord server. I've not been able to find any documentation out there aside from Twitter -> Discord bots. But it's clearly doable, as the site https://www.Zapier.com seems to offer exactly that.

I've been using discord.js and node.js for my projects so far.


Solution

  • I figured it out.

    // Discord Modules
    const Discord = require('discord.js')
    const fs = require('fs');
    const { prefix, token } = require('./config.js')
    
    // Express for the Heroku fix
    const express = require('express');
    const app = express();
    
    // Hook up to the server as a user
    const client = new Discord.Client()
    client.commands = new Discord.Collection()
    
    // Create a collection of available commands
    const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
    
    for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
    
        // set a new item in the Collection
        // with the key as the command name and the value as the exported module
        client.commands.set(command.name, command);
    }
    
    
    // Listen for incoming chat commands, and compare them to the collection.
    client.on('message', async message => {
      if (!message.content.startsWith(prefix) || message.author.bot) return;
    
      const args = message.content.slice(prefix.length).split(/ +/);
      const commandName = args.shift().toLowerCase();
      const command = client.commands.get(commandName);
    
      if (!client.commands.has(commandName)) return;
      
      if (command.args && !args.length) {
        return message.channel.reply(`You didn't provide any arguments`)
      }
    
      try {
        command.execute(message, args)
      } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
      }
    })
    
    
      //For avoidong Heroku $PORT error
    app.set('port', (process.env.PORT || 5000));
    
    app.get('/', function(request, response) {
        var result = 'App is running'
        response.send(result);
    }).listen(app.get('port'), function() {
        console.log('App is running, server is listening on port ', app.get('port'));
    });
    
    client.login(token)
    

    And the command to call in order to post a tweet

    // Twitter Modules
    const Twit = require('twit');
    const config = require('../config');
    const T = new Twit(config);
    
    module.exports = {
      name: 'tweet',
      description: 'create a tweet from a discord post',
      execute(message, args) {
        let discPost = args
        T.post('statuses/update', { status: discPost }, tweeted)
      }
    }
    
    // Make sure it worked!
    function tweeted (err, reply) {
      if (err !== undefined) {
        console.log(err)
      } else {
        console.log('Tweeted: ' + reply)
      }
    }
    

    Ugly little proof of concept, but it works.