Twitter bot that generates an image with your quote!
Tags: showdev, firstpost, node, javascript
Published: 2018-04-24 16:06:58

---
title: Twitter bot that generates an image with your quote!
published: true
description: Learning Javascript by making a Twitter bot.
tags: #showdev #firstpost #nodejs #javascript
cover_image: https://thepracticaldev.s3.amazonaws.com/i/s6i8emgfeidtv33mejti.jpg
---

In Twitter, I often see people tweeting inspirational, funny or even silly quote. I imagine, what if there's a twitter bot that generates an image with their quote in it? Like this :

![Copy and Pasting from Stack Overflow](https://thepracticaldev.s3.amazonaws.com/i/s6i8emgfeidtv33mejti.jpg)

So I decided to build one.

I have no experience creating an app with Javascript other than "copy this script to footer section" or "include this script in head tag", to get the experience and learning javascript, I chose to build this bot with Javascript.

Thankfully, this video tutorial by [Daniel Shiffman](https://www.youtube.com/user/shiffman) helps me a lot to get started.

{% youtube mUoIPmZ4KwA %}

(Also check [the amazing playlist](https://www.youtube.com/watch?v=RF5_MPSNAtU&list=PLRqwX-V7Uu6byiVX7_Z1rclitVhMBmNFQ))

##Setup Twitter Application

The setup is quite similar to this one, so You can follow this post to set up the Twitter Application. ðŸ˜…
{% link https://dev.to/omarhashimoto/how-to-build-a-simple-twitter-bot-in-17-lines-ofcode-2aan %}

###Listening to the user event
I want this bot to work when someone quotes any of this bot tweet. We are going to create a stream that listening to the user event :

```javascript
const stream = T.stream("user");
stream.on("quoted_tweet", tweetEvent);
```
if someone quoted any of this bot tweet it will execute `tweetEvent` callback, here's the code of `tweetEvent` callback :

```javascript
function tweetEvent(eventMsg) {

  const text = eventMsg.target_object.text;
  const from = `@${eventMsg.source.screen_name}`;
  const twit_id = eventMsg.target_object.id_str;

  if (eventMsg.event === "quoted_tweet") {
    const tweetMedia = imagePath => {
      try {
        var b64content = fs.readFileSync(imagePath, { encoding: "base64" });
        T.post("media/upload", { media_data: b64content }).then(response => {
          var mediaIdStr = response.data.media_id_string;
          var altText = "Image Quote Generated By Quotemakerbot";
          var meta_params = {
            media_id: mediaIdStr,
            alt_text: { text: altText }
          };

          T.post("media/metadata/create", meta_params).then(() => {
            var params = {
              status: `${from}`,
              in_reply_to_status_id: twit_id,
              media_ids: [mediaIdStr]
            };
            T.post("statuses/update", params).then(response => {
              console.log("Successfully post to twitter");
       
    //some code omitted

```
the `tweetMedia` is just a function that's accept an image path to post the image to Twitter, Here's the "actual" code that's doing the image processing :

```javascript
exports.processImage = async (from, text) => {
  const param = tweetUtil.getUnsplashParam(text)
  options = {
    url: `https://source.unsplash.com/1024x576/${param}`,
    dest: `${from}.jpg`
  }
  const { filename, image } = await download.image(options)
  const filteredImage = await ImageProcessor.filterImage(filename,`${from}-filtered.jpg`)
  setTimeout(function() {
  ImageProcessor.drawImageAndTextToCanvas(filteredImage,{
      text:tweetUtil.cleanAndTidyTweet(text),
      imageName: from+`-quoted.jpg`,
      username: from
    })
  }, 1500);
  return `${from}-quoted.jpg`
}
```

To be honest, I can't explain every part of the code, this bot was made 9 months ago, when I read the code again, I was like :

![I have no memory](https://thepracticaldev.s3.amazonaws.com/i/nd6wk8brbgvp5zuao4q0.gif)

But here's how this bot works in general :

1. Someone quotes this bot's tweet.
2. This bot will download images from Unsplash randomly or by specified category, for instance I add -coding option so it will download image with the coding category from Unsplash. Here's the image :
    ![Original Image](https://thepracticaldev.s3.amazonaws.com/i/ltuhc6et6es8xa5bfzy2.jpg)
3. Then, brightness and contrast of the image dropped a little bit to make the texts more readable.
    ![Filtered Image](https://thepracticaldev.s3.amazonaws.com/i/bor2shkbpg7obbu4e8js.jpg)
4. Draw the image and texts to canvas
    ![Finished Image](https://thepracticaldev.s3.amazonaws.com/i/s6i8emgfeidtv33mejti.jpg)
5. Post it to Twitter!

That's it, give it a try! [@quotemakerbot](https://twitter.com/quotemakerbot)

[Click here] (https://gist.github.com/nirzaq/088f95a984430535054e0ab002bdfb61) for the list of available options, if you don't add an option, the background image will be from the random category on Unsplash.

##Usage Example

Tweet format : -option (your quote)

![how to](https://thepracticaldev.s3.amazonaws.com/i/x3eptlhlmfs3u1ggsve0.png)

##Result
![Result](https://thepracticaldev.s3.amazonaws.com/i/2k5wsdd2i2gmnovyvdii.png)

  

PS : Sometimes this bot doesn't work as expected. ðŸ™‡