Writing A Twitter Bot in Golang Image

Writing A Twitter Bot in Golang

In this tutorial I’m going to be demonstrating how to build a twitter bot using go-twitter, a popular Go client library for the Twitter API.

I’ll be demonstrating how you can build a go based twitter bot that will be able to do such things as automatically reply to tweets and favourite tweets that contain a specific hashtag.

Connecting to Twitter

Just like with the Python version of this tutorial, you’ll have to create an app in twitter’s app control panel. Once you’ve created a new application, it should present you with all the secret tokens and keys that you need in order to proceed.

Writing our Basic Go Twitter Bot

Once you’ve got all the access tokens and secret tokens ready, it’s time to start implementing our Bot. Create a new file called twitter-bot.go and add the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main

import (
    "fmt"
    "log"
    "os"
    "os/signal"
    "syscall"
    
    "github.com/dghubble/go-twitter/twitter"
    "github.com/dghubble/oauth1"
)

func configure() {
    // Pass in your consumer key (API Key) and your Consumer Secret (API Secret) 
    config := oauth1.NewConfig("consumer-key", "consumer-secret")
    // Pass in your Access Token and your Access Token Secret
    token := oauth1.NewToken("access-token", "access-token-secret")
    httpClient := config.Client(oauth1.NoContext, token)
    client := twitter.NewClient(httpClient)
    
    
    demux := twitter.NewSwitchDemux()
    
    demux.Tweet = func(tweet *twitter.Tweet){
        fmt.Println(tweet.Text)
    }
    
    demux.DM = func(dm *twitter.DirectMessage){
        fmt.Println(dm.SenderID)
    }
    
    fmt.Println("Starting Stream...")
    
    // FILTER
	filterParams := &twitter.StreamFilterParams{
		Track:         []string{"cat"},
		StallWarnings: twitter.Bool(true),
	}
	stream, err := client.Streams.Filter(filterParams)
	if err != nil {
		log.Fatal(err)
	}
    
    // Receive messages until stopped or stream quits
	go demux.HandleChan(stream.Messages)

	// Wait for SIGINT and SIGTERM (HIT CTRL-C)
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Println(<-ch)

	fmt.Println("Stopping Stream...")
	stream.Stop()
    
}

func main() {
    fmt.Println("Go-Twitter Bot v0.01")
    configure()
}
Was This Post Helpful?
Submit a PR: Edit on Github