C#

This walkthrough will show you how to build an app that listens for tweets from a certain twitter account, and then routes that tweet to a phone number, through Live Link 365's SMS API.

This is not a production-ready application. Please take your time to enhance it for production so that it meets your specific business requirements.

Steps

Code

keyboard_arrow_down
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
    // _Step_1
    "llkAppKey": "someHexKey",
    "llkAppSecret": "someHexSecret",
    "defaultOrigin": "someOrigin",
    "consumerKey": "someHexKey",
    "consumerSecret": "someHexSecret",
    "token": "someHexToken",
    "tokenSecret": "someHexTokenSecret",
    "user":  
        {
            "userId": "userId",
            "phoneNumber": []
        }
}
 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
using System;
using System.IO;
using System.Collections;

using Newtonsoft.Json.Linq;
using Tweetinvi;
using Tweetinvi.Credentials;
using Tweetinvi.Models;

using socialMedia.Class;

namespace socialMedia
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            // _Step_3
            JObject properties = JObject.Parse(File.ReadAllText(@"../../Resources/properties.json")); //Get the properties to be used in the project

            // _Step_4
            MessageHandler messageHandler = new MessageHandler(properties.GetValue("llkAppKey").ToString(), properties.GetValue("llkAppSecret").ToString(), properties.GetValue("defaultOrigin").ToString()); //Initialize the message handler
            var userToken = properties.GetValue("user");

            // _Step_2
            long userId = (long)userToken["userId"];//Get Twitter userId
            JArray phoneNumbers = (JArray)userToken["phoneNumbers"];//Get the array/list of phoneNumbers which are going to be notified.

            //Set the credentials from your Twitter app
            Auth.SetUserCredentials(properties.GetValue("consumerKey").ToString(), properties.GetValue("consumerSecret").ToString(), properties.GetValue("token").ToString(), properties.GetValue("tokenSecret").ToString());

            var user = User.GetUserFromId(userId);//Get the user using the userId provided

            // _Step_6
            var stream = Tweetinvi.Stream.CreateUserStream();//Create a stream to start listening the user's activity
            stream.TweetCreatedByMe += (object sender, Tweetinvi.Events.TweetReceivedEventArgs tweetArgs) => {
                String tweetMessage = tweetArgs.Tweet.FullText; //Get the tweet text
                for (Int32 i = 0; i < phoneNumbers.Count; i++) {
                    messageHandler.sendMessage(tweetMessage, phoneNumbers[i].ToString());//Sends a message with the tweet to the desired phoneNumbers
                }
                Console.WriteLine(user.Name + ": " + tweetMessage + " @ " + tweetArgs.Tweet.CreatedAt.ToString("f"));
            };
            stream.StartStream();//Start the stream so it will start monitoring the user's activity
        }
    }
}
 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;

namespace socialMedia.Class
{

    public class MessageHandler
    {

        private String baseUrl = "https://livelink.sapdigitalinterconnect.com/api";
        private String appKey;
        private String appSecret;
        private String defaultOrigin;
        private WebProxy globalProxy;

        public MessageHandler()
        {
        }

        public MessageHandler(String appKey, String appSecret, String defaultOrigin = "", WebProxy proxy = null)
        {
            this.appKey = appKey;
            this.appSecret = appSecret;
            this.defaultOrigin = defaultOrigin;
            this.globalProxy = proxy;
        }

        // _Step_5
        public String GetAccessToken()
        {
            String oAuthUrl = this.baseUrl + "/oauth/token";
            String bearer = Convert.ToBase64String(Encoding.UTF8.GetBytes(this.appKey + ":" + this.appSecret));
            RestClient client = new RestClient(oAuthUrl);
            if (this.globalProxy != null) {
                client.Proxy = this.globalProxy;
                client.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            }
            RestRequest request = new RestRequest(Method.POST);
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddHeader("authorization", "Basic " + bearer);
            request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials", ParameterType.RequestBody);

            IRestResponse<oAuthToken> response = client.Execute<oAuthToken>(request);

            if (response.StatusCode != HttpStatusCode.OK) {
                Console.WriteLine("..... Error: " + response.StatusDescription);
                return "";
            }

            String accessToken = response.Data.access_token;
            return accessToken;
        }

        public void sendMessage(String message, String destination, String origin = "")
        {
            String messageUrl = this.baseUrl + "/v2/sms";
            Object messagePayload = new {
                message = message,
                origin =  origin == "" ? this.defaultOrigin : origin,
                destination = destination //Phone numbers have to be in E.164 format.
            };
            String messageData = JsonConvert.SerializeObject(messagePayload);
            String bearer = GetAccessToken();
            if (String.IsNullOrEmpty(bearer)) {
                return;
            }
            RestClient client = new RestClient(messageUrl);
            if (this.globalProxy != null) {
                client.Proxy = this.globalProxy;
                client.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            }

            RestRequest request = new RestRequest(Method.POST);
            request.AddHeader("authorization", "Bearer " + bearer);
            request.AddHeader("content-type", "application/json");
            request.AddParameter("application/json", messageData, ParameterType.RequestBody);

            IRestResponse response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK) {
                Console.WriteLine("..... failed to send message.");
                Console.WriteLine("..... Error: " + response.ErrorMessage);
            }
        }
    }
}