├── .gitignore ├── LICENSE ├── README.md ├── Tweety.Tests ├── TestsConstants.cs ├── Tweety.Tests.csproj ├── WebhookInterceptorTests.cs └── WebhookManagerTests.cs ├── Tweety.sln └── Tweety ├── Authentication ├── AuthHeaderBuilder.cs └── TweetyAuthContext.cs ├── DirectMessageSender.cs ├── Extensions └── DictionaryExt.cs ├── InterceptionResult.cs ├── Models ├── DirectMessageEvent.cs ├── DirectMessageResult.cs ├── Twitter │ ├── CRCResponseToken.cs │ ├── HashtagEntity.cs │ ├── MediaEntity.cs │ ├── MessageCreate.cs │ ├── NewDirectMessageModels.cs │ ├── SymbolEntity.cs │ ├── TwitterEntities.cs │ ├── TwitterError.cs │ ├── TwitterUser.cs │ ├── UrlEntity.cs │ ├── UserMentionEntity.cs │ ├── WebhookDMResult.cs │ └── WebhookRegistration.cs ├── TwitterEvent.cs └── TwitterEventType.cs ├── Result.cs ├── Tweety.csproj ├── TweetyException.cs └── Webhooks ├── SubscriptionsManager.cs ├── WebhookInterceptor.cs └── WebhooksManager.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Muhamed AlGhzawi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tweety 2 | Tweety is a server-side, .NET Standard Library to help managing Twitter Webhook APIs, 3 | Currently, *Account Activity API* is the only supported API, it provides **Direct Messages** webhook API. 4 | Read more about it: https://dev.twitter.com/webhooks. 5 | 6 | # NuGet 7 | [![NuGet](https://img.shields.io/badge/nuget-Tweety-blue.svg)](https://nuget.org/packages/Tweety/) 8 | 9 | 10 | # Before you start 11 | As of July, 20th 2017 - You have to request access to the webhook APIs from Twitter using this [Form](https://gnipinc.formstack.com/forms/account_activity_api_configuration_request_form), the process will take few day. 12 | Anyways, check this page before you start: https://dev.twitter.com/webhooks/account-activity. 13 | 14 | 15 | # How it works 16 | You **Register a webhook** by url, that's your server, to **Handle incoming messages**. 17 | Then you **Subscribe** to a webhook by `Webhook Id`, then your server will recieve **Events** for any incoming OR outgoing direct message for/ from the signed in/ subscribed user (in most cases, the user is a bot). 18 | 19 | 20 | # What for? 21 | Well, I'd say mainly for Bots, the **WebhooksManager** and the **SubscriptionsManager** will be used once, mostly to register and subscribe your bot twitter account to your server, so you can get any DM as an event and handle it. 22 | 23 | 24 | # Tweety APIs 25 | 26 | - **WebhooksManager**: Register a webhook, Get a list of registered webhooks and Unregister a webhook. 27 | 28 | - **SubscriptionsManager**: Subscribe to a webhook, Unsubscribe, or Check if the user is already subscribed or not. 29 | 30 | - **WebhookInterceptor**: Handles the *Challenge Response Check (CRC)* [ref](https://dev.twitter.com/webhooks/securing#required-challenge-response-check) requests from Twitter and invoking `Action` if received a direct message webhook event after chcecking if the event is really from Twitter or not [ref](https://dev.twitter.com/webhooks/securing#validating-the-signature-header).. will return a `InterceptionResult`, if IsHandled is true, then return the response to the client, otherwise, you've to handle the request. 31 | 32 | - **TweetyAuthContext**: Containes the needed information to perform authorizerd Twitter requests, i.e. Consumer Key/ Secret, Access Token/ Secret. 33 | 34 | - **DirectMessageSender**: Provides an easy way to send Direct Messages to a Twitter user by screen name. 35 | 36 | # Example: Registerig a Webhook: 37 | ```csharp 38 | TweetyAuthContext authContext = new Tweety.Authentication.TweetyAuthContext() 39 | { 40 | AccessSecret = ACCESS_TOKEN_SECRET, 41 | AccessToken = ACCESS_TOKEN, 42 | ConsumerKey = CONSUMER_KEY, 43 | ConsumerSecret = CONSUMER_SECRET 44 | }; 45 | 46 | WebhooksManager webhooksManager = new WebhooksManager(authContext); 47 | Result result = webhooksManager.RegisterWebhook("https://something.com/Twitbot"); 48 | 49 | if (result.Success) 50 | { 51 |     Console.WriteLine($"Webhook Id {result.Data.Id}"); 52 | } 53 | else 54 | { 55 | Console.WriteLine($"Failed to register webhook, Error: {result.Error.ToString()}"); 56 | } 57 | 58 | ``` 59 | # Example: Subscribing to a Webhook: 60 | 61 | ```csharp 62 | 63 | SubscriptionsManager subManager = new SubscriptionsManager(authContext); 64 | Result result = await subManager.Subscribe(webhookId); 65 | 66 | if(result.Success && result.Data) 67 | { 68 |     Console.WriteLine($"Successfully subscribed to {webhookId}"); 69 | } 70 | else 71 | { 72 | Console.WriteLine($"Failed to subscribe to a webhook, Error: {result.Error?.ToString() ?? "Error isn't available"}"); 73 | } 74 | ``` 75 | 76 | # Example: Intercepting server request: 77 | 78 | I've used Webhook Azure Function to test it, follow [Setup Azure Function](https://github.com/mmgrt/Tweety#setup-azure-function) below if you're interested. 79 | 80 | ```csharp 81 | WebhookInterceptor interceptor = new WebhookInterceptor(CONSUMER_SECRET); 82 | InterceptionResult result = await interceptor.InterceptIncomingRequest(requestMessage, onMessage); 83 | 84 | if (result.IsHandled) 85 | { 86 | return result.Response; 87 | } 88 | else 89 | { 90 | //handle req 91 | } 92 | //.. 93 | 94 | private void onMessage(DirectMessageEvent message) 95 | { 96 | Console.WriteLine($"Recieved {message.MessageText} from {message.Sender.Name}."); 97 | } 98 | ``` 99 | 100 | # Setup Azure Function 101 | - Go to [Azure Portal](https://portal.azure.com). 102 | - Create Azure Function App. 103 | - Create a `Generic Webhook` Function. 104 | - Import Tweety.dll: 105 | - Clone this repo. 106 | - Compile using Visual Studio 2017. 107 | - Create a 'bin' folder in your function folder (same level as `run.csx`). 108 | - Upload Tweety.dll to the bin folder. 109 | - Insert `#r "Tweety.dll"` at the head of the `run.csx` file (before the `using` statements). 110 | - In the `Run` method, intercept incoming requests, see the sample: [Intercepting server request](https://github.com/mmgrt/Tweety#sample-intercepting-server-request). 111 | 112 | 113 | # Todo 114 | - [ ] Provide better documentation. 115 | - [ ] Do the todos in the code :). 116 | 117 | 118 | # Find me 119 | 120 | - Twitter: [@mmg_rt](https://www.twitter.com/mmg_rt) 121 | 122 | - My blog: [Devread.net](http://devread.net) 123 | 124 | -------------------------------------------------------------------------------- /Tweety.Tests/TestsConstants.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Tweety.Authentication; 7 | 8 | namespace Tweety.Tests 9 | { 10 | public class TestsConstants 11 | { 12 | /// 13 | /// Auth context to use int tests. 14 | /// 15 | public static TweetyAuthContext AuthContext => new TweetyAuthContext() 16 | { 17 | AccessSecret = "", 18 | AccessToken = "", 19 | ConsumerKey = "", 20 | ConsumerSecret = "" 21 | }; 22 | 23 | 24 | /// 25 | /// Webhook Url to register. 26 | /// 27 | public static string WebhookUrl => ""; 28 | 29 | 30 | /// 31 | /// Webhook Id to test against, Will be set in the RegisterWebhookTest. 32 | /// 33 | public static string RegsiteredWebhookId { get; set; } = ""; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Tweety.Tests/Tweety.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | exe 5 | 6 | 7 | 8 | netcoreapp1.1 9 | 10 | exe 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Tweety.Tests/WebhookInterceptorTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Tweety.Webhooks; 8 | using Tweety.Models; 9 | using System.Security.Cryptography; 10 | using Newtonsoft.Json.Linq; 11 | 12 | namespace Tweety.Tests 13 | { 14 | [TestClass] 15 | public class WebhookInterceptorTests 16 | { 17 | 18 | [TestMethod] 19 | public async Task InterceptIncomingMessage_CRCTest() 20 | { 21 | 22 | string consumerKey = DateTime.Now.Ticks.ToString(); 23 | string crcToken = Guid.NewGuid().ToString(); 24 | 25 | HttpRequestMessage crcRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"http://localhost?crc_token={crcToken}"); 26 | WebhookInterceptor interceptor = new WebhookInterceptor(consumerKey); 27 | 28 | InterceptionResult result = await interceptor.InterceptIncomingRequest(crcRequestMessage, null); 29 | 30 | Assert.IsTrue(result.IsHandled); 31 | 32 | HMACSHA256 hmacSHA256Alog = new HMACSHA256(Encoding.UTF8.GetBytes(consumerKey)); 33 | 34 | byte[] computedHash = hmacSHA256Alog.ComputeHash(Encoding.UTF8.GetBytes(crcToken)); 35 | 36 | string expectedToken = $"sha256={Convert.ToBase64String(computedHash)}"; 37 | 38 | 39 | string actuallJson = await result.Response.Content.ReadAsStringAsync(); 40 | JObject actuallJsonObject = JObject.Parse(actuallJson); 41 | string actuallToken = actuallJsonObject["response_token"].ToString(); 42 | 43 | Assert.AreEqual(expectedToken, actuallToken); 44 | Assert.AreEqual(result.RequestMessage, crcRequestMessage); 45 | 46 | } 47 | 48 | 49 | [TestMethod] 50 | public async Task InterceptIncomingMessage_UnhandledTest() 51 | { 52 | string consumerKey = DateTime.Now.Ticks.ToString(); 53 | HttpRequestMessage emptyRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"http://localhost"); 54 | 55 | WebhookInterceptor interceptor = new WebhookInterceptor(consumerKey); 56 | 57 | InterceptionResult result = await interceptor.InterceptIncomingRequest(emptyRequestMessage, null); 58 | 59 | Assert.IsFalse(result.IsHandled); 60 | Assert.AreEqual(result.RequestMessage, emptyRequestMessage); 61 | } 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Tweety.Tests/WebhookManagerTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Tweety.Authentication; 3 | using static Tweety.Tests.TestsConstants; 4 | using Tweety.Webhooks; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | namespace Tweety.Tests 9 | { 10 | [TestClass] 11 | public class WebhookManagerTests 12 | { 13 | [TestMethod] 14 | [Priority(0)] 15 | public async Task GetRegisteredWebhookTest() 16 | { 17 | 18 | WebhooksManager webhookManager = new WebhooksManager(AuthContext); 19 | 20 | var result = await webhookManager.GetRegisteredWebhooks(); 21 | 22 | Assert.IsTrue(result.Success); 23 | Assert.IsTrue(result.Data.Count == 0); 24 | 25 | } 26 | 27 | [TestMethod] 28 | [Priority(1)] 29 | public async Task RegisterWebhookTest() 30 | { 31 | WebhooksManager webhookManager = new WebhooksManager(AuthContext); 32 | 33 | var result = await webhookManager.RegisterWebhook(WebhookUrl); 34 | 35 | Assert.IsTrue(result.Success); 36 | Assert.IsTrue(result.Data.IsValid); 37 | Assert.IsTrue(result.Data.RegisteredUrl == WebhookUrl); 38 | 39 | RegsiteredWebhookId = result.Data.Id; 40 | } 41 | 42 | 43 | 44 | [TestMethod] 45 | [Priority(2)] 46 | public async Task UnregisterWebhookTest() 47 | { 48 | WebhooksManager webhookManager = new WebhooksManager(AuthContext); 49 | 50 | var result = await webhookManager.UnregisterWebhook(RegsiteredWebhookId); 51 | 52 | Assert.IsTrue(result.Success); 53 | Assert.IsTrue(result.Data); 54 | 55 | } 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Tweety.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.16 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tweety", "Tweety\Tweety.csproj", "{E5EE35F3-040E-4225-AB1F-ED46A42697EC}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{63BCF10E-D539-4F67-91E3-601937294151}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{1B1BDF8E-DA37-4F03-BBC9-8E2EB5BD6210}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tweety.Tests", "Tweety.Tests\Tweety.Tests.csproj", "{C70D1903-9BB7-4A8A-B79B-7DBFC76721DD}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {E5EE35F3-040E-4225-AB1F-ED46A42697EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {E5EE35F3-040E-4225-AB1F-ED46A42697EC}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {E5EE35F3-040E-4225-AB1F-ED46A42697EC}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {E5EE35F3-040E-4225-AB1F-ED46A42697EC}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {C70D1903-9BB7-4A8A-B79B-7DBFC76721DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {C70D1903-9BB7-4A8A-B79B-7DBFC76721DD}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {C70D1903-9BB7-4A8A-B79B-7DBFC76721DD}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {C70D1903-9BB7-4A8A-B79B-7DBFC76721DD}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {E5EE35F3-040E-4225-AB1F-ED46A42697EC} = {63BCF10E-D539-4F67-91E3-601937294151} 34 | {C70D1903-9BB7-4A8A-B79B-7DBFC76721DD} = {1B1BDF8E-DA37-4F03-BBC9-8E2EB5BD6210} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /Tweety/Authentication/AuthHeaderBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Security.Cryptography; 6 | using System.Text; 7 | using Tweety.Extensions; 8 | 9 | namespace Tweety.Authentication 10 | { 11 | 12 | /// 13 | /// Twitter Authentication helper. 14 | /// 15 | public class AuthHeaderBuilder 16 | { 17 | 18 | /// 19 | /// Returns a ready 'OAuth ..' prefixed header to set in any call to Twitter API. 20 | /// 21 | /// Twitter app auth context. 22 | /// The Request Http method. 23 | /// The Request uri along with any query parameter. 24 | /// 25 | public static string Build(TweetyAuthContext authContext, HttpMethod method, string requestUrl) 26 | { 27 | 28 | if (!Uri.TryCreate(requestUrl, UriKind.RelativeOrAbsolute, out Uri resourceUri)) 29 | { 30 | throw new TweetyException("Invalid Resource Url format."); 31 | } 32 | 33 | if (authContext == null || !authContext.IsValid) 34 | { 35 | throw new TweetyException("Invalid Tweety Auth Context."); 36 | } 37 | 38 | string oauthVersion = "1.0"; 39 | string oauthSignatureMethod = "HMAC-SHA1"; 40 | 41 | // It could be any random string.. 42 | string oauthNonce = DateTime.Now.Ticks.ToString(); 43 | 44 | double epochTimeStamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; 45 | 46 | string oauthTimestamp = Convert.ToInt64(epochTimeStamp).ToString(); 47 | 48 | Dictionary signatureParams = new Dictionary(); 49 | signatureParams.Add("oauth_consumer_key", authContext.ConsumerKey); 50 | signatureParams.Add("oauth_nonce", oauthNonce); 51 | signatureParams.Add("oauth_signature_method", oauthSignatureMethod); 52 | signatureParams.Add("oauth_timestamp", oauthTimestamp); 53 | signatureParams.Add("oauth_token", authContext.AccessToken); 54 | signatureParams.Add("oauth_version", oauthVersion); 55 | 56 | Dictionary qParams = resourceUri.GetParams(); 57 | foreach (KeyValuePair qp in qParams) 58 | { 59 | signatureParams.Add(qp.Key, qp.Value); 60 | } 61 | 62 | string baseString = string.Join("&", signatureParams.OrderBy(kpv => kpv.Key).Select(kpv => $"{kpv.Key}={kpv.Value}")); 63 | 64 | string resourceUrl = requestUrl.Contains("?") ? requestUrl.Substring(0, requestUrl.IndexOf("?")) : requestUrl; 65 | baseString = string.Concat(method.Method.ToUpper(), "&", Uri.EscapeDataString(resourceUrl), "&", Uri.EscapeDataString(baseString)); 66 | 67 | string oauthSignatureKey = string.Concat(Uri.EscapeDataString(authContext.ConsumerSecret), "&", Uri.EscapeDataString(authContext.AccessSecret)); 68 | 69 | string oauthSignature; 70 | using (HMACSHA1 hasher = new HMACSHA1(Encoding.ASCII.GetBytes(oauthSignatureKey))) 71 | { 72 | oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString))); 73 | } 74 | 75 | string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + 76 | "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + 77 | "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + 78 | "oauth_version=\"{6}\""; 79 | 80 | string authHeader = string.Format(headerFormat, 81 | Uri.EscapeDataString(oauthNonce), 82 | Uri.EscapeDataString(oauthSignatureMethod), 83 | Uri.EscapeDataString(oauthTimestamp), 84 | Uri.EscapeDataString(authContext.ConsumerKey), 85 | Uri.EscapeDataString(authContext.AccessToken), 86 | Uri.EscapeDataString(oauthSignature), 87 | Uri.EscapeDataString(oauthVersion)); 88 | 89 | return authHeader; 90 | } 91 | 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Tweety/Authentication/TweetyAuthContext.cs: -------------------------------------------------------------------------------- 1 | namespace Tweety.Authentication 2 | { 3 | 4 | /// 5 | /// Required for any action, this represents the current user context. 6 | /// 7 | public class TweetyAuthContext 8 | { 9 | public string ConsumerKey { get; set; } 10 | public string ConsumerSecret { get; set; } 11 | public string AccessToken { get; set; } 12 | public string AccessSecret { get; set; } 13 | 14 | 15 | /// 16 | /// Check if the current auth context is valid or not. 17 | /// Null or Empty value for one on the auth properties will return false. 18 | /// 19 | public bool IsValid => !string.IsNullOrEmpty(ConsumerKey) && !string.IsNullOrEmpty(ConsumerSecret) && !string.IsNullOrEmpty(AccessToken) && !string.IsNullOrEmpty(AccessSecret); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Tweety/DirectMessageSender.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Tweety.Authentication; 9 | using Tweety.Models; 10 | using Tweety.Models.Twitter; 11 | 12 | namespace Tweety 13 | { 14 | 15 | /// 16 | /// Helper class to send Direct Message to twitter user using the screen name. 17 | /// 18 | public class DirectMessageSender 19 | { 20 | 21 | public TweetyAuthContext AuthContext { get; set; } 22 | 23 | public DirectMessageSender(TweetyAuthContext context) 24 | { 25 | AuthContext = context; 26 | } 27 | 28 | 29 | /// 30 | /// Send a direct message to User from the current user (using AuthContext). 31 | /// 32 | /// To (screen name without '@' sign) 33 | /// Message Text to send.. Less than 140 char. 34 | /// 35 | /// 36 | [Obsolete("Use SendAsync instead.")] 37 | public async Task> Send(string toScreenName, string messageText) 38 | { 39 | 40 | //TODO: Provide a generic class to make Twitter API Requests. 41 | 42 | if (string.IsNullOrEmpty(messageText)) 43 | { 44 | throw new TweetyException("You can't send an empty message."); 45 | } 46 | if (messageText.Length > 140) 47 | { 48 | throw new TweetyException("You can't send more than 140 char using this end point, use SendAsync instead."); 49 | } 50 | 51 | messageText = Uri.EscapeDataString(messageText); 52 | string resourceUrl = $"https://api.twitter.com/1.1/direct_messages/new.json?text={messageText}&screen_name={toScreenName}"; 53 | 54 | HttpResponseMessage response; 55 | using (HttpClient client = new HttpClient()) 56 | { 57 | 58 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl)); 59 | 60 | response = await client.PostAsync(resourceUrl, new StringContent("")); 61 | } 62 | 63 | if (response.StatusCode == HttpStatusCode.OK) 64 | { 65 | 66 | string msgCreateJson = await response.Content.ReadAsStringAsync(); 67 | MessageCreate mCreateObj = JsonConvert.DeserializeObject(msgCreateJson); 68 | return new Result(mCreateObj); 69 | } 70 | 71 | string jsonResponse = await response.Content.ReadAsStringAsync(); 72 | 73 | if (!string.IsNullOrEmpty(jsonResponse)) 74 | { 75 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 76 | return new Result(err); 77 | } 78 | else 79 | { 80 | //TODO: Provide a way to return httpstatus code 81 | 82 | return new Result(); 83 | } 84 | } 85 | 86 | 87 | /// 88 | /// Send a direct message to a user by userId, from the current user (using AuthContext). 89 | /// 90 | /// The Twitter User Id to send the message to. 91 | /// The text of the message, should be less than 10,000 chars. 92 | /// 93 | public async Task> SendAsync(long userId, string messageText) 94 | { 95 | 96 | //TODO: Provide a generic class to make Twitter API Requests. 97 | 98 | if (string.IsNullOrEmpty(messageText)) 99 | { 100 | throw new TweetyException("You can't send an empty message."); 101 | } 102 | 103 | if (messageText.Length > 10000) 104 | { 105 | throw new TweetyException("Invalid message, the length of the message should be less than 10000 chars."); 106 | } 107 | 108 | if (userId == default(long)) 109 | { 110 | throw new TweetyException("Invalid userId."); 111 | } 112 | 113 | string resourceUrl = $"https://api.twitter.com/1.1/direct_messages/events/new.json"; 114 | 115 | NewDirectMessageObject newDmEvent = new NewDirectMessageObject(); 116 | newDmEvent.@event = new Event() { type = "message_create" }; 117 | newDmEvent.@event.message_create = new NewEvent_MessageCreate() { message_data = new NewEvent_MessageData { text = messageText }, target = new Target { recipient_id = userId.ToString() } }; 118 | string jsonObj = JsonConvert.SerializeObject(newDmEvent); 119 | 120 | 121 | HttpResponseMessage response; 122 | using (HttpClient client = new HttpClient()) 123 | { 124 | 125 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl)); 126 | 127 | 128 | response = await client.PostAsync(resourceUrl, new StringContent(jsonObj, Encoding.UTF8, "application/json")); 129 | } 130 | 131 | if (response.StatusCode == HttpStatusCode.OK) 132 | { 133 | string msgCreateJson = await response.Content.ReadAsStringAsync(); 134 | NewDmResult mCreateObj = JsonConvert.DeserializeObject(msgCreateJson); 135 | return new Result(mCreateObj.@event); 136 | } 137 | 138 | string jsonResponse = await response.Content.ReadAsStringAsync(); 139 | 140 | if (!string.IsNullOrEmpty(jsonResponse)) 141 | { 142 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 143 | return new Result(err); 144 | } 145 | else 146 | { 147 | //TODO: Provide a way to return httpstatus code 148 | 149 | return new Result(); 150 | } 151 | 152 | } 153 | 154 | 155 | 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /Tweety/Extensions/DictionaryExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text.RegularExpressions; 4 | 5 | namespace Tweety.Extensions 6 | { 7 | internal static class DictionaryExt 8 | { 9 | public static Dictionary GetParams(this Uri uri) 10 | { 11 | try 12 | { 13 | MatchCollection matches = Regex.Matches(uri.AbsoluteUri, @"[\?&](([^&=]+)=([^&=#]*))", RegexOptions.Compiled); 14 | Dictionary keyValues = new Dictionary(matches.Count); 15 | foreach (Match m in matches) 16 | { 17 | keyValues.Add(Uri.UnescapeDataString(m.Groups[2].Value), Uri.UnescapeDataString(m.Groups[3].Value)); 18 | } 19 | 20 | return keyValues; 21 | } 22 | catch (Exception ex) 23 | { 24 | return new Dictionary(); 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Tweety/InterceptionResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Text; 6 | 7 | namespace Tweety 8 | { 9 | 10 | /// 11 | /// HttpRequestMessage Interception Result, See: . 12 | /// 13 | public class InterceptionResult 14 | { 15 | /// 16 | /// Determines of the request is handled internally, in this case, you should return . 17 | /// 18 | public bool IsHandled { get; internal set; } 19 | 20 | /// 21 | /// The to return to the client if is true. 22 | /// If is false, this will be empty with status code: . 23 | /// 24 | public HttpResponseMessage Response { get; internal set; } 25 | 26 | /// 27 | /// The original request message, for reference purposes only. 28 | /// 29 | public HttpRequestMessage RequestMessage { get; internal set; } 30 | 31 | private InterceptionResult() 32 | { 33 | 34 | } 35 | 36 | internal static InterceptionResult CreateHandled(HttpResponseMessage response, HttpRequestMessage request) 37 | { 38 | return new InterceptionResult() 39 | { 40 | IsHandled = true, 41 | RequestMessage = request, 42 | Response = response 43 | }; 44 | } 45 | 46 | internal static InterceptionResult CreateUnhandled(HttpResponseMessage response, HttpRequestMessage request) 47 | { 48 | return new InterceptionResult() 49 | { 50 | IsHandled = false, 51 | RequestMessage = request, 52 | Response = response 53 | }; 54 | } 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Tweety/Models/DirectMessageEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Tweety.Models.Twitter; 5 | 6 | namespace Tweety.Models 7 | { 8 | public class DirectMessageEvent : TwitterEvent 9 | { 10 | 11 | public TwitterUser Recipient { get; set; } 12 | public TwitterUser Sender { get; set; } 13 | 14 | public string MessageText { get; set; } 15 | public TwitterEntities MessageEntities { get; set; } 16 | 17 | public string JsonSource { get; set; } 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /Tweety/Models/DirectMessageResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models 6 | { 7 | 8 | /// 9 | /// The result of sending a new direct message. 10 | /// 11 | public class DirectMessageResult 12 | { 13 | /// 14 | /// Created Timestamp. 15 | /// 16 | public DateTime Created { get; set; } 17 | 18 | 19 | /// 20 | /// Message Id. 21 | /// 22 | public string Id { get; set; } 23 | 24 | 25 | /// 26 | /// The Twitter User Id who the message was sent to. 27 | /// 28 | public string RecipientId { get; set; } 29 | 30 | 31 | /// 32 | /// The Twitter User Id who sent the message. 33 | /// 34 | public string SenderId { get; set; } 35 | 36 | 37 | /// 38 | /// The sent message text. 39 | /// 40 | public string MessageText { get; set; } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/CRCResponseToken.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Tweety.Models.Twitter 7 | { 8 | internal class CRCResponseToken 9 | { 10 | [JsonProperty("response_token")] 11 | public string Token { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/HashtagEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | public class HashtagEntity 8 | { 9 | 10 | public string text { get; set; } 11 | public int[] indices { get; set; } 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/MediaEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | 8 | public class MediaEntity 9 | { 10 | public long id { get; set; } 11 | public string id_str { get; set; } 12 | public int[] indices { get; set; } 13 | public string media_url { get; set; } 14 | public string media_url_https { get; set; } 15 | public string url { get; set; } 16 | public string display_url { get; set; } 17 | public string expanded_url { get; set; } 18 | public string type { get; set; } 19 | public Sizes sizes { get; set; } 20 | } 21 | 22 | public class Sizes 23 | { 24 | public TwitterSizeMedium medium { get; set; } 25 | public TwitterSizeThumb thumb { get; set; } 26 | public TwitterSizeSmall small { get; set; } 27 | public TwitterSizeLarge large { get; set; } 28 | } 29 | 30 | public class TwitterSizeMedium 31 | { 32 | public int w { get; set; } 33 | public int h { get; set; } 34 | public string resize { get; set; } 35 | } 36 | 37 | public class TwitterSizeThumb 38 | { 39 | public int w { get; set; } 40 | public int h { get; set; } 41 | public string resize { get; set; } 42 | } 43 | 44 | public class TwitterSizeSmall 45 | { 46 | public int w { get; set; } 47 | public int h { get; set; } 48 | public string resize { get; set; } 49 | } 50 | 51 | public class TwitterSizeLarge 52 | { 53 | public int w { get; set; } 54 | public int h { get; set; } 55 | public string resize { get; set; } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/MessageCreate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | 8 | public class MessageCreate 9 | { 10 | public long id { get; set; } 11 | public string id_str { get; set; } 12 | public string text { get; set; } 13 | public TwitterFullUser sender { get; set; } 14 | public int sender_id { get; set; } 15 | public string sender_id_str { get; set; } 16 | public string sender_screen_name { get; set; } 17 | public TwitterFullUser recipient { get; set; } 18 | public long recipient_id { get; set; } 19 | public string recipient_id_str { get; set; } 20 | public string recipient_screen_name { get; set; } 21 | public string created_at { get; set; } 22 | public TwitterEntities entities { get; set; } 23 | } 24 | 25 | public class TwitterFullUser 26 | { 27 | public long id { get; set; } 28 | public string id_str { get; set; } 29 | public string name { get; set; } 30 | public string screen_name { get; set; } 31 | public string location { get; set; } 32 | public string description { get; set; } 33 | public string url { get; set; } 34 | public TwitterEntities entities { get; set; } 35 | public bool _protected { get; set; } 36 | public int followers_count { get; set; } 37 | public int friends_count { get; set; } 38 | public int listed_count { get; set; } 39 | public string created_at { get; set; } 40 | public int favourites_count { get; set; } 41 | public string utc_offset { get; set; } 42 | public string time_zone { get; set; } 43 | public bool geo_enabled { get; set; } 44 | public bool verified { get; set; } 45 | public int statuses_count { get; set; } 46 | public string lang { get; set; } 47 | public bool contributors_enabled { get; set; } 48 | public bool is_translator { get; set; } 49 | public bool is_translation_enabled { get; set; } 50 | public string profile_background_color { get; set; } 51 | public string profile_background_image_url { get; set; } 52 | public string profile_background_image_url_https { get; set; } 53 | public bool profile_background_tile { get; set; } 54 | public string profile_image_url { get; set; } 55 | public string profile_image_url_https { get; set; } 56 | public string profile_banner_url { get; set; } 57 | public string profile_link_color { get; set; } 58 | public string profile_sidebar_border_color { get; set; } 59 | public string profile_sidebar_fill_color { get; set; } 60 | public string profile_text_color { get; set; } 61 | public bool profile_use_background_image { get; set; } 62 | public bool has_extended_profile { get; set; } 63 | public bool default_profile { get; set; } 64 | public bool default_profile_image { get; set; } 65 | public bool following { get; set; } 66 | public bool follow_request_sent { get; set; } 67 | public bool notifications { get; set; } 68 | public string translator_type { get; set; } 69 | } 70 | 71 | 72 | 73 | } 74 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/NewDirectMessageModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | 8 | public class NewDirectMessageObject 9 | { 10 | public Event @event { get; set; } 11 | } 12 | 13 | public class Event 14 | { 15 | public string type { get; set; } 16 | public NewEvent_MessageCreate message_create { get; set; } 17 | } 18 | 19 | public class NewEvent_MessageCreate 20 | { 21 | public Target target { get; set; } 22 | public NewEvent_MessageData message_data { get; set; } 23 | } 24 | 25 | public class NewEvent_MessageData 26 | { 27 | public string text { get; set; } 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/SymbolEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | public class SymbolEntity 8 | { 9 | 10 | public string text { get; set; } 11 | public int[] indices { get; set; } 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/TwitterEntities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Tweety.Models.Twitter; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | public class TwitterEntities 8 | { 9 | public List hashtags { get; set; } 10 | public List symbols { get; set; } 11 | public List user_mentions { get; set; } 12 | public List urls { get; set; } 13 | public List media { get; set; } 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/TwitterError.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace Tweety.Models.Twitter 8 | { 9 | 10 | public class TwitterError 11 | { 12 | [JsonProperty("errors")] 13 | public List Errors { get; set; } 14 | 15 | public override string ToString() 16 | { 17 | return string.Join("\n", Errors.Select(err => $"Error Code: {err.Code}, Error Message: {err.Message}")); 18 | } 19 | } 20 | 21 | public class Error 22 | { 23 | 24 | [JsonProperty("code")] 25 | public int Code { get; set; } 26 | 27 | [JsonProperty("message")] 28 | public string Message { get; set; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/TwitterUser.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Tweety.Models.Twitter 4 | { 5 | public class TwitterUser 6 | { 7 | [JsonProperty("id")] 8 | public string Id { get; set; } 9 | 10 | [JsonProperty("created_timestamp")] 11 | public long CreatedTimestamp { get; set; } 12 | 13 | [JsonProperty("name")] 14 | public string Name { get; set; } 15 | 16 | [JsonProperty("screen_name")] 17 | public string ScreenName { get; set; } 18 | 19 | [JsonProperty("location")] 20 | public string Location { get; set; } 21 | 22 | [JsonProperty("description")] 23 | public string Description { get; set; } 24 | 25 | [JsonProperty("url")] 26 | public string Url { get; set; } 27 | 28 | [JsonProperty("_protected")] 29 | public bool IsProtected { get; set; } 30 | 31 | [JsonProperty("verified")] 32 | public bool IsVerified { get; set; } 33 | 34 | [JsonProperty("followers_count")] 35 | public int FollowersCount { get; set; } 36 | 37 | [JsonProperty("friends_count")] 38 | public int FriendsCount { get; set; } 39 | 40 | [JsonProperty("statuses_count")] 41 | public int StatusesCount { get; set; } 42 | 43 | [JsonProperty("profile_image_url")] 44 | public string ProfileImage { get; set; } 45 | 46 | [JsonProperty("profile_image_url_https")] 47 | public string ProfileImageHttps { get; set; } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/UrlEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | public class UrlEntity 8 | { 9 | public string url { get; set; } 10 | public string expanded_url { get; set; } 11 | public string display_url { get; set; } 12 | public int[] indices { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/UserMentionEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models.Twitter 6 | { 7 | public class UserMentionEntity 8 | { 9 | public string screen_name { get; set; } 10 | public string name { get; set; } 11 | public long id { get; set; } 12 | public string id_str { get; set; } 13 | public int[] indices { get; set; } 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/WebhookDMResult.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace Tweety.Models.Twitter 8 | { 9 | 10 | public class WebhookDMResult 11 | { 12 | [JsonProperty("direct_message_events")] 13 | public List Events { get; set; } 14 | 15 | [JsonProperty("users")] 16 | public Dictionary Users { get; set; } 17 | 18 | public static implicit operator DirectMessageEvent(WebhookDMResult result) 19 | { 20 | DirectMessageEvent dmEvent = new DirectMessageEvent(); 21 | 22 | DMEvent tdmEvent = result.Events.First(); 23 | 24 | dmEvent.Id = tdmEvent.id; 25 | dmEvent.Created = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(tdmEvent.created_timestamp); 26 | dmEvent.Type = tdmEvent.type == "message_create" ? TwitterEventType.MessageCreate : TwitterEventType.Unknown; 27 | 28 | dmEvent.MessageEntities = tdmEvent.message_create?.message_data?.entities; 29 | if (tdmEvent.message_create.message_data.attachment != null) 30 | { 31 | dmEvent.MessageEntities.media = new List(); 32 | dmEvent.MessageEntities.media.Add(tdmEvent.message_create.message_data.attachment.media); 33 | } 34 | 35 | 36 | dmEvent.MessageText = tdmEvent.message_create?.message_data?.text; 37 | dmEvent.Recipient = result.Users.Where(u => u.Value.Id == tdmEvent.message_create.target.recipient_id)?.FirstOrDefault().Value; 38 | dmEvent.Sender = result.Users.Where(u => u.Value.Id == tdmEvent.message_create.sender_id)?.FirstOrDefault().Value; 39 | 40 | return dmEvent; 41 | } 42 | } 43 | 44 | public class NewDmResult 45 | { 46 | public DMEvent @event { get; set; } 47 | } 48 | 49 | public class DMEvent 50 | { 51 | public string type { get; set; } 52 | public string id { get; set; } 53 | public long created_timestamp { get; set; } 54 | public Message message_create { get; set; } 55 | 56 | public static implicit operator DirectMessageResult(DMEvent dmevent) 57 | { 58 | DirectMessageResult res = new DirectMessageResult(); 59 | res.Created = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(dmevent.created_timestamp); 60 | res.Id = dmevent.id; 61 | res.MessageText = dmevent.message_create.message_data.text; 62 | res.RecipientId = dmevent.message_create.target.recipient_id; 63 | res.SenderId = dmevent.message_create.sender_id; 64 | 65 | return res; 66 | } 67 | } 68 | 69 | public class Message 70 | { 71 | public Target target { get; set; } 72 | public string sender_id { get; set; } 73 | public Message_Data message_data { get; set; } 74 | } 75 | 76 | public class Target 77 | { 78 | public string recipient_id { get; set; } 79 | } 80 | 81 | public class Message_Data 82 | { 83 | public string text { get; set; } 84 | public TwitterEntities entities { get; set; } 85 | public Attachment attachment { get; set; } 86 | } 87 | 88 | public class Attachment 89 | { 90 | public string type { get; set; } 91 | public MediaEntity media { get; set; } 92 | 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /Tweety/Models/Twitter/WebhookRegistration.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Tweety.Models.Twitter 7 | { 8 | public class WebhookRegistration 9 | { 10 | 11 | [JsonProperty("id")] 12 | public string Id { get; set; } 13 | 14 | [JsonProperty("url")] 15 | public string RegisteredUrl { get; set; } 16 | 17 | [JsonProperty("valid")] 18 | public bool IsValid { get; set; } 19 | 20 | [JsonProperty("created_timestamp ")] 21 | public long CreatedTimestamp { get; set; } 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Tweety/Models/TwitterEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models 6 | { 7 | public class TwitterEvent 8 | { 9 | public string Id { get; internal set; } 10 | public TwitterEventType Type { get; internal set; } 11 | public DateTime Created { get; internal set; } 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Tweety/Models/TwitterEventType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety.Models 6 | { 7 | public enum TwitterEventType 8 | { 9 | MessageCreate, 10 | Unknown 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Tweety/Result.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Tweety.Models.Twitter; 5 | 6 | namespace Tweety 7 | { 8 | 9 | /// 10 | /// Wrapper to wrap any result for better errors underdstanding. 11 | /// 12 | /// 13 | public class Result 14 | { 15 | public Result() 16 | { 17 | Success = false; 18 | } 19 | public Result(T data) 20 | { 21 | Data = data; 22 | Success = true; 23 | } 24 | 25 | public Result(TwitterError err) 26 | { 27 | Error = err; 28 | Success = false; 29 | 30 | } 31 | 32 | public T Data { get; private set; } 33 | 34 | public TwitterError Error { get; private set; } 35 | 36 | public bool Success { get; private set; } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Tweety/Tweety.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard1.3 5 | true 6 | true 7 | 8 | 9 | 10 | bin\Debug\netstandard1.3\Tweety.xml 11 | 12 | 13 | 14 | 15 | bin\Release\netstandard1.3\Tweety.xml 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Tweety/TweetyException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Tweety 6 | { 7 | 8 | /// 9 | /// Exception thrown by Tweety. 10 | /// 11 | public class TweetyException : Exception 12 | { 13 | internal TweetyException(string message) : base(message) 14 | { 15 | 16 | } 17 | 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Tweety/Webhooks/SubscriptionsManager.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Tweety.Authentication; 9 | using Tweety.Models; 10 | using Tweety.Models.Twitter; 11 | 12 | namespace Tweety.Webhooks 13 | { 14 | 15 | /// 16 | /// This class will help in managing the webhook subscription. 17 | /// 18 | public class SubscriptionsManager 19 | { 20 | public TweetyAuthContext AuthContext { get; set; } 21 | 22 | public SubscriptionsManager(TweetyAuthContext context) 23 | { 24 | AuthContext = context; 25 | } 26 | 27 | 28 | /// 29 | /// Subscribe current user (from the auth context) to a webhook by Id. 30 | /// 31 | /// Webhook Id to subscribe to. 32 | /// true indicates successfull subscribtion. 33 | public async Task> Subscribe(string webhookId) 34 | { 35 | 36 | if (string.IsNullOrEmpty(webhookId)) 37 | { 38 | throw new ArgumentException(nameof(webhookId)); 39 | } 40 | 41 | //TODO: Provide a generic class to make Twitter API Requests. 42 | string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}/subscriptions.json"; 43 | 44 | HttpResponseMessage response; 45 | using (HttpClient client = new HttpClient()) 46 | { 47 | 48 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl)); 49 | 50 | response = await client.PostAsync(resourceUrl, new StringContent("")); 51 | } 52 | 53 | 54 | if (response.StatusCode == HttpStatusCode.NoContent) 55 | { 56 | return new Result(true); 57 | } 58 | 59 | string jsonResponse = await response.Content.ReadAsStringAsync(); 60 | 61 | if (!string.IsNullOrEmpty(jsonResponse)) 62 | { 63 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 64 | return new Result(err); 65 | } 66 | else 67 | { 68 | //TODO: Provide a way to return httpstatus code 69 | 70 | return new Result(); 71 | } 72 | 73 | } 74 | 75 | /// 76 | /// Checks if the current user (from the auth context) is subscribed to a webhook by Id. 77 | /// 78 | /// Webhook Id to check against. 79 | /// true indicates existed subscribtion. 80 | public async Task> CheckSubscription(string webhookId) 81 | { 82 | 83 | if (string.IsNullOrEmpty(webhookId)) 84 | { 85 | throw new ArgumentException(nameof(webhookId)); 86 | } 87 | 88 | //TODO: Provide a generic class to make Twitter API Requests. 89 | string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}/subscriptions.json"; 90 | 91 | HttpResponseMessage response; 92 | using (HttpClient client = new HttpClient()) 93 | { 94 | 95 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Get, resourceUrl)); 96 | 97 | response = await client.GetAsync(resourceUrl); 98 | } 99 | 100 | string jsonResponse = await response.Content.ReadAsStringAsync(); 101 | 102 | if (response.StatusCode == HttpStatusCode.NoContent) 103 | { 104 | return new Result(true); 105 | } 106 | 107 | if (!string.IsNullOrEmpty(jsonResponse)) 108 | { 109 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 110 | if(err.Errors.Count == 1 && err.Errors[0].Code == 34) 111 | { 112 | // Twitter API will return : {"code":34,"message":"Sorry, that page does not exist."} if you try to check a webhook with 0 subscribers, 113 | // Which means, you're not subscribed. 114 | return new Result(false); 115 | } 116 | 117 | return new Result(err); 118 | } 119 | else 120 | { 121 | 122 | //TODO: Provide a way to return httpstatus code 123 | return new Result(); 124 | } 125 | 126 | 127 | } 128 | 129 | 130 | /// 131 | /// Unsubscribe current user (from the auth context) from a webhook by Id. 132 | /// 133 | /// Webhook Id to unsubscribe from. 134 | /// true indicates successful deletion. 135 | public async Task> Unsubscribe(string webhookId) 136 | { 137 | 138 | if (string.IsNullOrEmpty(webhookId)) 139 | { 140 | throw new ArgumentException(nameof(webhookId)); 141 | } 142 | 143 | //TODO: Provide a generic class to make Twitter API Requests. 144 | string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}/subscriptions.json"; 145 | 146 | HttpResponseMessage response; 147 | using (HttpClient client = new HttpClient()) 148 | { 149 | 150 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Delete, resourceUrl)); 151 | 152 | response = await client.DeleteAsync(resourceUrl); 153 | } 154 | 155 | string jsonResponse = await response.Content.ReadAsStringAsync(); 156 | 157 | if (response.StatusCode == HttpStatusCode.NoContent) 158 | { 159 | return new Result(true); 160 | } 161 | 162 | if (!string.IsNullOrEmpty(jsonResponse)) 163 | { 164 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 165 | if (err.Errors.Count == 1 && err.Errors[0].Code == 34) 166 | { 167 | // Twitter API will return : {"code":34,"message":"Sorry, that page does not exist."} if you try to check a webhook with 0 subscribers, 168 | // Which means, you're not subscribed. 169 | return new Result(true); 170 | } 171 | 172 | return new Result(err); 173 | } 174 | else 175 | { 176 | 177 | //TODO: Provide a way to return httpstatus code 178 | return new Result(); 179 | } 180 | 181 | 182 | } 183 | 184 | 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /Tweety/Webhooks/WebhookInterceptor.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net.Http; 6 | using System.Security.Cryptography; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using Tweety.Extensions; 10 | using Tweety.Models; 11 | using Tweety.Models.Twitter; 12 | 13 | namespace Tweety.Webhooks 14 | { 15 | 16 | /// 17 | /// This class is responsible to intercept incoming requests to the server 18 | /// and handle them properly. 19 | /// 20 | public class WebhookInterceptor 21 | { 22 | 23 | /// 24 | /// Twitter App Consumer Secret. 25 | /// Used to Hash incoming/ outgoing data. 26 | /// 27 | public string ConsumerSecret { get; set; } 28 | 29 | 30 | /// 31 | /// Create a new instance of with your Twitter App Consumer Key. 32 | /// 33 | /// 34 | /// Twitter App Consumer Key, used for hashing. 35 | public WebhookInterceptor(string consumerSecret) 36 | { 37 | ConsumerSecret = consumerSecret; 38 | } 39 | 40 | 41 | /// 42 | /// Intercept incoming requests to the server to handle them according to Twitter Documentation, Currently: 43 | /// - Challenge Response Check. 44 | /// - Incoming DirectMessage. 45 | /// 46 | /// Thr request message object you recieved. 47 | /// If this is an incoming direct message, this callback will be fired along with the message object . 48 | /// 49 | /// Interception result. 50 | /// 51 | public async Task InterceptIncomingRequest(HttpRequestMessage requestMessage, Action OnDirectMessageRecieved) 52 | { 53 | if (string.IsNullOrEmpty(ConsumerSecret)) 54 | { 55 | throw new TweetyException("Consumer Secret can't be null."); 56 | } 57 | 58 | if (requestMessage.Method == HttpMethod.Get) 59 | { 60 | Dictionary requestParams = requestMessage.RequestUri.GetParams(); 61 | if (!requestParams.ContainsKey("crc_token")) 62 | { 63 | 64 | goto Finally; 65 | } 66 | 67 | // Challenge Response Check Request: 68 | string crcToken = requestParams["crc_token"]; 69 | HttpResponseMessage response = AcceptChallenge(crcToken); 70 | 71 | return InterceptionResult.CreateHandled(response, requestMessage); 72 | } 73 | else if (requestMessage.Method == HttpMethod.Post) 74 | { 75 | 76 | if (!requestMessage.Headers.Contains("x-twitter-webhooks-signature")) 77 | { 78 | goto Finally; 79 | } 80 | 81 | string payloadSignature = requestMessage.Headers.GetValues("x-twitter-webhooks-signature").First(); 82 | string payload = await requestMessage.Content.ReadAsStringAsync(); 83 | 84 | 85 | bool signatureMatch = IsValidTwitterPostRequest(payloadSignature, payload); 86 | if (!signatureMatch) 87 | { 88 | //This is interseting, a twitter signature key 'x-twitter-webhooks-signature' is there but it's wrong..! 89 | return InterceptionResult.CreateHandled(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest), requestMessage); 90 | 91 | } 92 | 93 | try 94 | { 95 | WebhookDMResult dmResult = JsonConvert.DeserializeObject(payload); 96 | DirectMessageEvent eventResult = dmResult; 97 | eventResult.JsonSource = payload; 98 | 99 | OnDirectMessageRecieved?.Invoke(eventResult); 100 | } 101 | catch 102 | { 103 | //Failed to deserialize twitter direct message, 104 | //TODO: Handle in a better way.. perhaps send the json? 105 | } 106 | 107 | } 108 | 109 | Finally: 110 | return InterceptionResult.CreateUnhandled(OK(), requestMessage); 111 | } 112 | 113 | 114 | private HttpResponseMessage AcceptChallenge(string crcToken) 115 | { 116 | 117 | byte[] hashKeyArray = Encoding.UTF8.GetBytes(ConsumerSecret); 118 | byte[] crcTokenArray = Encoding.UTF8.GetBytes(crcToken); 119 | 120 | HMACSHA256 hmacSHA256Alog = new HMACSHA256(hashKeyArray); 121 | 122 | byte[] computedHash = hmacSHA256Alog.ComputeHash(crcTokenArray); 123 | 124 | string challengeToken = $"sha256={Convert.ToBase64String(computedHash)}"; 125 | 126 | CRCResponseToken responseToken = new CRCResponseToken() 127 | { 128 | Token = challengeToken 129 | }; 130 | 131 | string jsonResponse = JsonConvert.SerializeObject(responseToken); 132 | 133 | return OK(jsonResponse); 134 | } 135 | private bool IsValidTwitterPostRequest(string twWebhookSignature, string payload) 136 | { 137 | byte[] hashKeyArray = Encoding.UTF8.GetBytes(ConsumerSecret); 138 | HMACSHA256 hmacSHA256Alog = new HMACSHA256(hashKeyArray); 139 | 140 | byte[] computedHash = hmacSHA256Alog.ComputeHash(Encoding.UTF8.GetBytes(payload)); 141 | string localHashedSignature = $"sha256={Convert.ToBase64String(computedHash)}"; 142 | 143 | return localHashedSignature == twWebhookSignature; 144 | } 145 | 146 | private static HttpResponseMessage OK(string content = "") => new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent(content) }; 147 | 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /Tweety/Webhooks/WebhooksManager.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Tweety.Authentication; 9 | using Tweety.Models; 10 | using Tweety.Models.Twitter; 11 | 12 | namespace Tweety.Webhooks 13 | { 14 | 15 | /// 16 | /// This class will help in managing the webhooks registrations. 17 | /// 18 | public class WebhooksManager 19 | { 20 | 21 | public TweetyAuthContext AuthContext { get; set; } 22 | 23 | public WebhooksManager(TweetyAuthContext context) 24 | { 25 | AuthContext = context; 26 | } 27 | 28 | 29 | /// 30 | /// Retrieve a list of associated with the user (from the auth context). 31 | /// 32 | /// 33 | public async Task>> GetRegisteredWebhooks() 34 | { 35 | 36 | 37 | string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks.json"; 38 | 39 | HttpResponseMessage response; 40 | using (HttpClient client = new HttpClient()) 41 | { 42 | 43 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Get, resourceUrl)); 44 | 45 | response = await client.GetAsync(resourceUrl); 46 | } 47 | string jsonResponse = await response.Content.ReadAsStringAsync(); 48 | 49 | if (response.StatusCode == HttpStatusCode.OK) 50 | { 51 | List subs = JsonConvert.DeserializeObject>(jsonResponse); 52 | return new Result>(subs); 53 | } 54 | 55 | 56 | if (!string.IsNullOrEmpty(jsonResponse)) 57 | { 58 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 59 | return new Result>(err); 60 | } 61 | else 62 | { 63 | return new Result>(); 64 | } 65 | 66 | } 67 | 68 | 69 | /// 70 | /// Register a new webhook url using the current user (from the auth context). 71 | /// 72 | /// The webhook url to register. 73 | /// 74 | public async Task> RegisterWebhook(string url) 75 | { 76 | if (string.IsNullOrEmpty(url)) 77 | { 78 | throw new ArgumentException(nameof(url)); 79 | } 80 | 81 | //TODO: Provide a generic class to make Twitter API Requests. 82 | string urlParam = Uri.EscapeUriString(url); 83 | string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks.json?url={urlParam}"; 84 | 85 | HttpResponseMessage response; 86 | using (HttpClient client = new HttpClient()) 87 | { 88 | 89 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl)); 90 | 91 | response = await client.PostAsync(resourceUrl, new StringContent("")); 92 | } 93 | 94 | string jsonResponse = await response.Content.ReadAsStringAsync(); 95 | 96 | if (response.StatusCode == HttpStatusCode.OK) 97 | { 98 | WebhookRegistration sub = JsonConvert.DeserializeObject(jsonResponse); 99 | return new Result(sub); 100 | } 101 | 102 | if (!string.IsNullOrEmpty(jsonResponse)) 103 | { 104 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 105 | return new Result(err); 106 | } 107 | else 108 | { 109 | //TODO: Provide a way to return httpstatus code 110 | 111 | return new Result(); 112 | } 113 | 114 | } 115 | 116 | 117 | /// 118 | /// Unregister a webhook from current user (from the auth context) by Id. 119 | /// 120 | /// The Webhook Id to unregister. 121 | /// 122 | public async Task> UnregisterWebhook(string webhookId) 123 | { 124 | 125 | //TODO: Provide a generic class to make Twitter API Requests. 126 | 127 | string resourceUrl = $"https://api.twitter.com/1.1/account_activity/webhooks/{webhookId}.json"; 128 | 129 | HttpResponseMessage response; 130 | using (HttpClient client = new HttpClient()) 131 | { 132 | 133 | client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Delete, resourceUrl)); 134 | 135 | response = await client.DeleteAsync(resourceUrl); 136 | } 137 | 138 | if (response.StatusCode == HttpStatusCode.NoContent) 139 | { 140 | return new Result(true); 141 | } 142 | 143 | string jsonResponse = await response.Content.ReadAsStringAsync(); 144 | 145 | if (!string.IsNullOrEmpty(jsonResponse)) 146 | { 147 | TwitterError err = JsonConvert.DeserializeObject(jsonResponse); 148 | return new Result(err); 149 | } 150 | else 151 | { 152 | //TODO: Provide a way to return httpstatus code 153 | 154 | return new Result(); 155 | } 156 | 157 | } 158 | 159 | 160 | 161 | } 162 | } 163 | --------------------------------------------------------------------------------