├── .github └── workflows │ └── codeql-analysis.yml ├── .gitignore ├── Images ├── AzureFunctionsIntegrateSettings.PNG ├── ChannelSecret.PNG ├── LineSearchDotNetCoreFxRepoBot.PNG ├── WebJobSettings.PNG └── WebJobSettingsForTranslateBot.PNG ├── LICENSE ├── LineBotMessageCollector ├── .gitignore ├── Function1.cs ├── LineBotMessageCollector.csproj ├── Properties │ ├── serviceDependencies.json │ └── serviceDependencies.local.json └── host.json ├── LineBotMessageWebJob ├── Functions.cs ├── LineBotMessageWebJob.csproj └── Program.cs ├── LineBotNet.Core ├── ApiExceptions.cs ├── Configuration │ ├── AppSettings.cs │ └── AppSettingsBase.cs ├── GitHubApi │ ├── Data │ │ └── GitHubSearchResult.cs │ └── GitHubSearchApi.cs ├── LineBotNet.Core.csproj └── MicrosoftApi │ ├── AdmAccessToken.cs │ ├── AdmAuthentication.cs │ └── TranslateApi.cs ├── LineBotNet.sln ├── LineSearchDotNetCoreFxRepoBot ├── Functions.cs ├── LineSearchDotNetCoreFxRepoBot.csproj ├── Program.cs └── README.md ├── LineTranslateBot ├── Functions.cs ├── LineTranslateBot.csproj ├── Program.cs └── README.md └── README.md /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 5 * * 3' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['csharp'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | with: 35 | # We must fetch at least the immediate parents so that if this is 36 | # a pull request then we can checkout the head. 37 | fetch-depth: 2 38 | 39 | # If this run was triggered by a pull request event, then checkout 40 | # the head of the pull request instead of the merge commit. 41 | - run: git checkout HEAD^2 42 | if: ${{ github.event_name == 'pull_request' }} 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.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 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | # NuGet v3's project.json files produces more ignoreable files 154 | *.nuget.props 155 | *.nuget.targets 156 | 157 | # Microsoft Azure Build Output 158 | csx/ 159 | *.build.csdef 160 | 161 | # Microsoft Azure Emulator 162 | ecf/ 163 | rcf/ 164 | 165 | # Microsoft Azure ApplicationInsights config file 166 | ApplicationInsights.config 167 | 168 | # Windows Store app package directory 169 | AppPackages/ 170 | BundleArtifacts/ 171 | 172 | # Visual Studio cache files 173 | # files ending in .cache can be ignored 174 | *.[Cc]ache 175 | # but keep track of directories ending in .cache 176 | !*.[Cc]ache/ 177 | 178 | # Others 179 | ClientBin/ 180 | ~$* 181 | *~ 182 | *.dbmdl 183 | *.dbproj.schemaview 184 | *.pfx 185 | *.publishsettings 186 | node_modules/ 187 | orleans.codegen.cs 188 | 189 | # RIA/Silverlight projects 190 | Generated_Code/ 191 | 192 | # Backup & report files from converting an old project file 193 | # to a newer Visual Studio version. Backup files are not needed, 194 | # because we have git ;-) 195 | _UpgradeReport_Files/ 196 | Backup*/ 197 | UpgradeLog*.XML 198 | UpgradeLog*.htm 199 | 200 | # SQL Server files 201 | *.mdf 202 | *.ldf 203 | 204 | # Business Intelligence projects 205 | *.rdl.data 206 | *.bim.layout 207 | *.bim_*.settings 208 | 209 | # Microsoft Fakes 210 | FakesAssemblies/ 211 | 212 | # GhostDoc plugin setting file 213 | *.GhostDoc.xml 214 | 215 | # Node.js Tools for Visual Studio 216 | .ntvs_analysis.dat 217 | 218 | # Visual Studio 6 build log 219 | *.plg 220 | 221 | # Visual Studio 6 workspace options file 222 | *.opt 223 | 224 | # Visual Studio LightSwitch build output 225 | **/*.HTMLClient/GeneratedArtifacts 226 | **/*.DesktopClient/GeneratedArtifacts 227 | **/*.DesktopClient/ModelManifest.xml 228 | **/*.Server/GeneratedArtifacts 229 | **/*.Server/ModelManifest.xml 230 | _Pvt_Extensions 231 | 232 | # Paket dependency manager 233 | .paket/paket.exe 234 | 235 | # FAKE - F# Make 236 | .fake/ 237 | -------------------------------------------------------------------------------- /Images/AzureFunctionsIntegrateSettings.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kiyoaki/LineBot-Sample-for-DotNet/671f627e2806ba932476603fb057f21599b2d452/Images/AzureFunctionsIntegrateSettings.PNG -------------------------------------------------------------------------------- /Images/ChannelSecret.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kiyoaki/LineBot-Sample-for-DotNet/671f627e2806ba932476603fb057f21599b2d452/Images/ChannelSecret.PNG -------------------------------------------------------------------------------- /Images/LineSearchDotNetCoreFxRepoBot.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kiyoaki/LineBot-Sample-for-DotNet/671f627e2806ba932476603fb057f21599b2d452/Images/LineSearchDotNetCoreFxRepoBot.PNG -------------------------------------------------------------------------------- /Images/WebJobSettings.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kiyoaki/LineBot-Sample-for-DotNet/671f627e2806ba932476603fb057f21599b2d452/Images/WebJobSettings.PNG -------------------------------------------------------------------------------- /Images/WebJobSettingsForTranslateBot.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kiyoaki/LineBot-Sample-for-DotNet/671f627e2806ba932476603fb057f21599b2d452/Images/WebJobSettingsForTranslateBot.PNG -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Kiyoaki Tsurutani 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 | -------------------------------------------------------------------------------- /LineBotMessageCollector/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # Azure Functions localsettings file 5 | local.settings.json 6 | 7 | # User-specific files 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | 28 | # Visual Studio 2015 cache/options directory 29 | .vs/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # MSTest test Results 34 | [Tt]est[Rr]esult*/ 35 | [Bb]uild[Ll]og.* 36 | 37 | # NUNIT 38 | *.VisualState.xml 39 | TestResult.xml 40 | 41 | # Build Results of an ATL Project 42 | [Dd]ebugPS/ 43 | [Rr]eleasePS/ 44 | dlldata.c 45 | 46 | # DNX 47 | project.lock.json 48 | project.fragment.lock.json 49 | artifacts/ 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # NCrunch 117 | _NCrunch_* 118 | .*crunch*.local.xml 119 | nCrunchTemp_* 120 | 121 | # MightyMoose 122 | *.mm.* 123 | AutoTest.Net/ 124 | 125 | # Web workbench (sass) 126 | .sass-cache/ 127 | 128 | # Installshield output folder 129 | [Ee]xpress/ 130 | 131 | # DocProject is a documentation generator add-in 132 | DocProject/buildhelp/ 133 | DocProject/Help/*.HxT 134 | DocProject/Help/*.HxC 135 | DocProject/Help/*.hhc 136 | DocProject/Help/*.hhk 137 | DocProject/Help/*.hhp 138 | DocProject/Help/Html2 139 | DocProject/Help/html 140 | 141 | # Click-Once directory 142 | publish/ 143 | 144 | # Publish Web Output 145 | *.[Pp]ublish.xml 146 | *.azurePubxml 147 | # TODO: Comment the next line if you want to checkin your web deploy settings 148 | # but database connection strings (with potential passwords) will be unencrypted 149 | #*.pubxml 150 | *.publishproj 151 | 152 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 153 | # checkin your Azure Web App publish settings, but sensitive information contained 154 | # in these scripts will be unencrypted 155 | PublishScripts/ 156 | 157 | # NuGet Packages 158 | *.nupkg 159 | # The packages folder can be ignored because of Package Restore 160 | **/packages/* 161 | # except build/, which is used as an MSBuild target. 162 | !**/packages/build/ 163 | # Uncomment if necessary however generally it will be regenerated when needed 164 | #!**/packages/repositories.config 165 | # NuGet v3's project.json files produces more ignoreable files 166 | *.nuget.props 167 | *.nuget.targets 168 | 169 | # Microsoft Azure Build Output 170 | csx/ 171 | *.build.csdef 172 | 173 | # Microsoft Azure Emulator 174 | ecf/ 175 | rcf/ 176 | 177 | # Windows Store app package directories and files 178 | AppPackages/ 179 | BundleArtifacts/ 180 | Package.StoreAssociation.xml 181 | _pkginfo.txt 182 | 183 | # Visual Studio cache files 184 | # files ending in .cache can be ignored 185 | *.[Cc]ache 186 | # but keep track of directories ending in .cache 187 | !*.[Cc]ache/ 188 | 189 | # Others 190 | ClientBin/ 191 | ~$* 192 | *~ 193 | *.dbmdl 194 | *.dbproj.schemaview 195 | *.jfm 196 | *.pfx 197 | *.publishsettings 198 | node_modules/ 199 | orleans.codegen.cs 200 | 201 | # Since there are multiple workflows, uncomment next line to ignore bower_components 202 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 203 | #bower_components/ 204 | 205 | # RIA/Silverlight projects 206 | Generated_Code/ 207 | 208 | # Backup & report files from converting an old project file 209 | # to a newer Visual Studio version. Backup files are not needed, 210 | # because we have git ;-) 211 | _UpgradeReport_Files/ 212 | Backup*/ 213 | UpgradeLog*.XML 214 | UpgradeLog*.htm 215 | 216 | # SQL Server files 217 | *.mdf 218 | *.ldf 219 | 220 | # Business Intelligence projects 221 | *.rdl.data 222 | *.bim.layout 223 | *.bim_*.settings 224 | 225 | # Microsoft Fakes 226 | FakesAssemblies/ 227 | 228 | # GhostDoc plugin setting file 229 | *.GhostDoc.xml 230 | 231 | # Node.js Tools for Visual Studio 232 | .ntvs_analysis.dat 233 | 234 | # Visual Studio 6 build log 235 | *.plg 236 | 237 | # Visual Studio 6 workspace options file 238 | *.opt 239 | 240 | # Visual Studio LightSwitch build output 241 | **/*.HTMLClient/GeneratedArtifacts 242 | **/*.DesktopClient/GeneratedArtifacts 243 | **/*.DesktopClient/ModelManifest.xml 244 | **/*.Server/GeneratedArtifacts 245 | **/*.Server/ModelManifest.xml 246 | _Pvt_Extensions 247 | 248 | # Paket dependency manager 249 | .paket/paket.exe 250 | paket-files/ 251 | 252 | # FAKE - F# Make 253 | .fake/ 254 | 255 | # JetBrains Rider 256 | .idea/ 257 | *.sln.iml 258 | 259 | # CodeRush 260 | .cr/ 261 | 262 | # Python Tools for Visual Studio (PTVS) 263 | __pycache__/ 264 | *.pyc -------------------------------------------------------------------------------- /LineBotMessageCollector/Function1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Azure.WebJobs; 4 | using Microsoft.Azure.WebJobs.Extensions.Http; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.Primitives; 7 | using System; 8 | using System.Linq; 9 | using System.Security.Cryptography; 10 | using System.Text; 11 | using System.Threading.Tasks; 12 | 13 | namespace LineBotMessageCollector 14 | { 15 | public static class Function1 16 | { 17 | [FunctionName("CollectMessage")] 18 | public static async Task Run( 19 | [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, 20 | ILogger log) 21 | { 22 | StringValues headers; 23 | if (!req.Headers.TryGetValue("X-Line-Signature", out headers)) 24 | { 25 | return null; 26 | } 27 | 28 | var channelSignature = headers.FirstOrDefault(); 29 | if (channelSignature == null) 30 | { 31 | return null; 32 | } 33 | 34 | if (string.IsNullOrEmpty(LineSettings.ChannelSecret)) 35 | { 36 | log.LogWarning("Please set ChannelSecret in App Settings"); 37 | return null; 38 | } 39 | 40 | var secret = Encoding.UTF8.GetBytes(LineSettings.ChannelSecret); 41 | var content = await req.ReadAsStringAsync(); 42 | var body = Encoding.UTF8.GetBytes(content); 43 | 44 | using (var hmacsha256 = new HMACSHA256(secret)) 45 | { 46 | var signature = Convert.ToBase64String(hmacsha256.ComputeHash(body)); 47 | if (channelSignature != signature) 48 | { 49 | return null; 50 | } 51 | } 52 | 53 | return new OkObjectResult(content); 54 | } 55 | } 56 | } 57 | 58 | internal static class LineSettings 59 | { 60 | internal static readonly string ChannelSecret = Environment.GetEnvironmentVariable("ChannelSecret", EnvironmentVariableTarget.Process); 61 | } 62 | -------------------------------------------------------------------------------- /LineBotMessageCollector/LineBotMessageCollector.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net6.0 4 | v3 5 | 6 | 7 | 8 | 9 | 10 | 11 | PreserveNewest 12 | 13 | 14 | PreserveNewest 15 | Never 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /LineBotMessageCollector/Properties/serviceDependencies.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "appInsights1": { 4 | "type": "appInsights" 5 | } 6 | } 7 | } -------------------------------------------------------------------------------- /LineBotMessageCollector/Properties/serviceDependencies.local.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "appInsights1": { 4 | "type": "appInsights.sdk" 5 | } 6 | } 7 | } -------------------------------------------------------------------------------- /LineBotMessageCollector/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingExcludedTypes": "Request", 6 | "samplingSettings": { 7 | "isEnabled": true 8 | } 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /LineBotMessageWebJob/Functions.cs: -------------------------------------------------------------------------------- 1 | using LineMessaging; 2 | using Microsoft.Azure.WebJobs; 3 | using Newtonsoft.Json; 4 | using System; 5 | using System.Configuration; 6 | using System.IO; 7 | using System.Threading.Tasks; 8 | 9 | namespace LineBotMessageWebJob 10 | { 11 | public class Functions 12 | { 13 | private static readonly LineOAuthClient oAuthClient = 14 | new LineOAuthClient(ConfigurationManager.AppSettings["ChannelId"], ConfigurationManager.AppSettings["ChannelSecret"]); 15 | 16 | private static LineOAuthTokenResponse tokenResponse; 17 | 18 | public static async Task ProcessQueueMessage([QueueTrigger("line-bot-workitems")] string message, TextWriter log) 19 | { 20 | log.WriteLine(message); 21 | LineWebhookContent data; 22 | try 23 | { 24 | data = JsonConvert.DeserializeObject(message); 25 | } 26 | catch (Exception ex) 27 | { 28 | log.WriteLine("Ignore deserialization error: " + ex.ToString()); 29 | return; 30 | } 31 | 32 | if (data?.Events != null) 33 | { 34 | foreach (var webhookEvent in data.Events) 35 | { 36 | log.WriteLine("event type: " + webhookEvent.Type); 37 | switch (webhookEvent.Type) 38 | { 39 | case WebhookRequestEventType.Message: 40 | if (webhookEvent.Message.Type == MessageType.Text) 41 | { 42 | log.WriteLine("text: " + webhookEvent.Message.Text); 43 | 44 | if (tokenResponse == null || tokenResponse.ExpiresIn < DateTime.Now.AddDays(-1)) 45 | { 46 | tokenResponse = await oAuthClient.GetAccessToken(); 47 | } 48 | 49 | var client = new LineMessagingClient(tokenResponse.AccessToken); 50 | await client.PushMessage(webhookEvent.Source.UserId, webhookEvent.Message.Text); 51 | } 52 | break; 53 | 54 | default: 55 | log.WriteLine("Not implemented event type: " + webhookEvent.Type); 56 | break; 57 | } 58 | } 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /LineBotMessageWebJob/LineBotMessageWebJob.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /LineBotMessageWebJob/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using Microsoft.Extensions.Logging; 3 | using System.Threading.Tasks; 4 | 5 | namespace LineBotMessageWebJob 6 | { 7 | class Program 8 | { 9 | static async Task Main() 10 | { 11 | var builder = new HostBuilder(); 12 | builder.ConfigureWebJobs(b => 13 | { 14 | b.AddAzureStorageCoreServices(); 15 | b.AddAzureStorageBlobs(); 16 | b.AddAzureStorageQueues(); 17 | }); 18 | var host = builder.Build(); 19 | using (host) 20 | { 21 | await host.RunAsync(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LineBotNet.Core/ApiExceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | 4 | namespace LineBotNet.Core 5 | { 6 | public class RequestException : Exception 7 | { 8 | public override string Message { get; } 9 | 10 | public RequestException(HttpResponseMessage response) 11 | { 12 | var statusCode = (int)response.StatusCode; 13 | var reasonPhrase = response.ReasonPhrase; 14 | var content = response.Content.ReadAsStringAsync().Result; 15 | 16 | Message = string.Join(Environment.NewLine, 17 | $"StatusCode: {statusCode}", 18 | $"ReasonPhrase: {reasonPhrase}", 19 | $"Content: {content}"); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /LineBotNet.Core/Configuration/AppSettings.cs: -------------------------------------------------------------------------------- 1 | namespace LineBotNet.Core.Configuration 2 | { 3 | public class AppSettings : AppSettingsBase 4 | { 5 | protected AppSettings() { } 6 | 7 | public static string MsTranslateApiClientId => Setting("MsTranslateApiClientId"); 8 | 9 | public static string MsTranslateApiClientSecret => Setting("MsTranslateApiClientSecret"); 10 | 11 | public static string GitHubAccessToken => Setting("GitHubAccessToken"); 12 | } 13 | } -------------------------------------------------------------------------------- /LineBotNet.Core/Configuration/AppSettingsBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Specialized; 3 | using System.Configuration; 4 | 5 | namespace LineBotNet.Core.Configuration 6 | { 7 | public class AppSettingsBase 8 | { 9 | protected AppSettingsBase() { } 10 | 11 | protected static NameValueCollection AppSettings = ConfigurationManager.AppSettings; 12 | 13 | protected static string Setting(string key, string defaultValue = null) 14 | { 15 | return AppSettings[key] ?? defaultValue; 16 | } 17 | 18 | protected static int SettingAsInt(string key, int defaultValue = default(int)) 19 | { 20 | int ret; 21 | return int.TryParse(AppSettings[key], out ret) ? ret : defaultValue; 22 | } 23 | 24 | protected static float SettingAsFloat(string key, float defaultValue = default(float)) 25 | { 26 | float ret; 27 | return float.TryParse(AppSettings[key], out ret) ? ret : defaultValue; 28 | } 29 | 30 | protected static double SettingAsDouble(string key, double defaultValue = default(double)) 31 | { 32 | double ret; 33 | return double.TryParse(AppSettings[key], out ret) ? ret : defaultValue; 34 | } 35 | 36 | protected static bool SettingAsBool(string key, bool defaultValue = default(bool)) 37 | { 38 | bool ret; 39 | return bool.TryParse(AppSettings[key], out ret) ? ret : defaultValue; 40 | } 41 | 42 | protected static DateTime SettingAsDateTime(string key, DateTime defaultValue = default(DateTime)) 43 | { 44 | DateTime ret; 45 | return DateTime.TryParse(AppSettings[key], out ret) ? ret : defaultValue; 46 | } 47 | 48 | protected static T SettingAsEnum(string key, T defaultValue = default(T)) 49 | where T : struct 50 | { 51 | T ret; 52 | return Enum.TryParse(AppSettings[key], out ret) ? ret : defaultValue; 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /LineBotNet.Core/GitHubApi/Data/GitHubSearchResult.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace LineBotNet.Core.GitHubApi.Data 4 | { 5 | public class GitHubSearchResult 6 | { 7 | [JsonProperty("items")] 8 | public GitHubSearchResultItem[] Items { get; set; } 9 | } 10 | 11 | public class GitHubSearchResultItem 12 | { 13 | [JsonProperty("url")] 14 | public string Url { get; set; } 15 | } 16 | 17 | public class GitHubSearchDetailItem 18 | { 19 | [JsonProperty("name")] 20 | public string Name { get; set; } 21 | 22 | [JsonProperty("path")] 23 | public string Path { get; set; } 24 | 25 | [JsonProperty("html_url")] 26 | public string HtmlUrl { get; set; } 27 | 28 | [JsonProperty("content")] 29 | public string Content { get; set; } 30 | 31 | [JsonProperty("message")] 32 | public string Message { get; set; } 33 | 34 | [JsonIgnore] 35 | public bool IsCallLimitExceeded => !string.IsNullOrEmpty(Message) && Message.StartsWith("API rate limit exceeded"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LineBotNet.Core/GitHubApi/GitHubSearchApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using LineBotNet.Core.Configuration; 8 | using LineBotNet.Core.GitHubApi.Data; 9 | using Newtonsoft.Json; 10 | 11 | namespace LineBotNet.Core.GitHubApi 12 | { 13 | public class GitHubSearchApi 14 | { 15 | private readonly TextWriter _log; 16 | public GitHubSearchApi() { } 17 | public GitHubSearchApi(TextWriter log) 18 | { 19 | _log = log; 20 | } 21 | 22 | private const string SearchUrlBase = "https://api.github.com/search/code?q={0}+in:file+filename:.cs+repo:dotnet/corefx"; 23 | private const string UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0"; 24 | private const int ResultCount = 3; 25 | 26 | public async Task Search(string query) 27 | { 28 | try 29 | { 30 | using (var httpClient = new HttpClient()) 31 | { 32 | httpClient.DefaultRequestHeaders.Add("Authorization", "token " + AppSettings.GitHubAccessToken); 33 | httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent); 34 | var response = await httpClient.GetAsync(string.Format(SearchUrlBase, query)); 35 | 36 | if (!response.IsSuccessStatusCode) 37 | { 38 | throw new RequestException(response); 39 | } 40 | 41 | var searchResultJson = await response.Content.ReadAsStringAsync(); 42 | var searchResult = JsonConvert.DeserializeObject(searchResultJson); 43 | 44 | var detailSearchResultResponse = await Task.WhenAll(searchResult.Items 45 | .Take(ResultCount) 46 | .OrderBy(_ => Guid.NewGuid()) 47 | .Select(async resultItem => 48 | { 49 | using (var httpClientForTask = new HttpClient()) 50 | { 51 | httpClientForTask.DefaultRequestHeaders.Add("Authorization", "token " + AppSettings.GitHubAccessToken); 52 | httpClientForTask.DefaultRequestHeaders.Add("User-Agent", UserAgent); 53 | var res = await httpClientForTask.GetAsync(resultItem.Url); 54 | return await res.Content.ReadAsStringAsync(); 55 | } 56 | })); 57 | 58 | var isCallLimitExceeded = false; 59 | return detailSearchResultResponse.Select(json => 60 | { 61 | _log?.WriteLine("DetailItem: " + json); 62 | 63 | var item = JsonConvert.DeserializeObject(json); 64 | if (string.IsNullOrEmpty(item.Content)) 65 | { 66 | return null; 67 | } 68 | 69 | if (isCallLimitExceeded) 70 | { 71 | return null; 72 | } 73 | 74 | if (item.IsCallLimitExceeded) 75 | { 76 | isCallLimitExceeded = true; 77 | return "Search limit exceeded. Please try later."; 78 | } 79 | 80 | return string.Join(Environment.NewLine, 81 | $"FileName: {item.Name}", 82 | $"URL: {item.HtmlUrl}", 83 | "", 84 | $"{Encoding.UTF8.GetString(Convert.FromBase64String(item.Content))}"); 85 | }) 86 | .Where(x => x != null) 87 | .ToArray(); 88 | } 89 | } 90 | catch (Exception ex) 91 | { 92 | _log?.WriteLine(string.Join(Environment.NewLine, 93 | $"Message: {ex.Message}", 94 | $"Source: {ex.Source}", 95 | "", 96 | $"StackTrace: {ex.StackTrace}")); 97 | 98 | return new[] { "Error has occuerd." }; 99 | } 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /LineBotNet.Core/LineBotNet.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /LineBotNet.Core/MicrosoftApi/AdmAccessToken.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace LineBotNet.Core.MicrosoftApi 4 | { 5 | public class AdmAccessToken 6 | { 7 | [JsonProperty("access_token")] 8 | public string Token { get; set; } 9 | 10 | [JsonProperty("token_type")] 11 | public string TokenType { get; set; } 12 | 13 | [JsonProperty("expires_in")] 14 | public string ExpiresIn { get; set; } 15 | 16 | [JsonProperty("scope")] 17 | public string Scope { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LineBotNet.Core/MicrosoftApi/AdmAuthentication.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using LineBotNet.Core.Configuration; 7 | using Newtonsoft.Json; 8 | 9 | namespace LineBotNet.Core.MicrosoftApi 10 | { 11 | public class AdmAuthentication 12 | { 13 | public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; 14 | private const string ScopeUrl = "http://api.microsofttranslator.com"; 15 | private readonly string _clientId; 16 | private readonly string _clientSecret; 17 | private readonly Timer _accessTokenRenewer; 18 | 19 | private const int RefreshTokenDuration = 9; 20 | 21 | private static volatile AdmAuthentication _instance; 22 | private static readonly object SyncRoot = new object(); 23 | 24 | private AdmAuthentication() 25 | { 26 | _clientId = AppSettings.MsTranslateApiClientId; 27 | _clientSecret = AppSettings.MsTranslateApiClientSecret; 28 | AccessToken = GetToken().Result; 29 | _accessTokenRenewer = new Timer(OnTokenExpiredCallback, this, TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1)); 30 | } 31 | 32 | public static AdmAuthentication Instance 33 | { 34 | get 35 | { 36 | if (_instance == null) 37 | { 38 | lock (SyncRoot) 39 | { 40 | if (_instance == null) 41 | _instance = new AdmAuthentication(); 42 | } 43 | } 44 | 45 | return _instance; 46 | } 47 | } 48 | 49 | public AdmAccessToken AccessToken { get; private set; } 50 | 51 | private void RenewAccessToken() 52 | { 53 | AccessToken = GetToken().Result; 54 | Console.WriteLine($"Renewed token for user: {_clientId} is: {AccessToken.Token}"); 55 | } 56 | 57 | private async Task GetToken() 58 | { 59 | using (var httpClient = new HttpClient()) 60 | { 61 | var response = await httpClient.PostAsync(DatamarketAccessUri, 62 | new FormUrlEncodedContent(new Dictionary 63 | { 64 | ["grant_type"] = "client_credentials", 65 | ["client_id"] = _clientId, 66 | ["client_secret"] = _clientSecret, 67 | ["scope"] = ScopeUrl 68 | })); 69 | 70 | if (!response.IsSuccessStatusCode) 71 | { 72 | throw new RequestException(response); 73 | } 74 | 75 | var responseBody = await response.Content.ReadAsStringAsync(); 76 | return JsonConvert.DeserializeObject(responseBody); 77 | } 78 | } 79 | 80 | private void OnTokenExpiredCallback(object stateInfo) 81 | { 82 | try 83 | { 84 | RenewAccessToken(); 85 | } 86 | catch (Exception ex) 87 | { 88 | Console.WriteLine($"Failed renewing access token. Details: {ex.Message}"); 89 | } 90 | finally 91 | { 92 | try 93 | { 94 | _accessTokenRenewer.Change(TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1)); 95 | } 96 | catch (Exception ex) 97 | { 98 | Console.WriteLine($"Failed to reschedule the timer to renew access token. Details: {ex.Message}"); 99 | } 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /LineBotNet.Core/MicrosoftApi/TranslateApi.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Net.Http.Headers; 3 | using System.Web; 4 | using System.Xml; 5 | using LineBotNet.Core.MicrosoftApi; 6 | 7 | namespace LineBotNet.Core 8 | { 9 | public class TranslateApi 10 | { 11 | public string Translate(string text, string from = "en", string to = "ja") 12 | { 13 | using (var httpClient = new HttpClient()) 14 | { 15 | var uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to; 16 | httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AdmAuthentication.Instance.AccessToken.Token); 17 | var response = httpClient.GetAsync(uri).Result; 18 | if (!response.IsSuccessStatusCode) 19 | { 20 | throw new RequestException(response); 21 | } 22 | 23 | using (var result = response.Content.ReadAsStreamAsync().Result) 24 | { 25 | using (var reader = XmlReader.Create(result)) 26 | { 27 | return reader.ReadElementString(); 28 | } 29 | 30 | } 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LineBotNet.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32210.308 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LineBotNet.Core", "LineBotNet.Core\LineBotNet.Core.csproj", "{241125A3-1CAA-4E48-90EF-EB5C02B02B60}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LineBotMessageWebJob", "LineBotMessageWebJob\LineBotMessageWebJob.csproj", "{E85C7C31-FA78-4B5A-AF31-1B4B54AE302B}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LineSearchDotNetCoreFxRepoBot", "LineSearchDotNetCoreFxRepoBot\LineSearchDotNetCoreFxRepoBot.csproj", "{0A36C39F-9CCC-4180-A23B-8F38BE4F17C6}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LineTranslateBot", "LineTranslateBot\LineTranslateBot.csproj", "{FC0CDDFD-EBD1-489C-826A-B3261931EAE7}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LineBotMessageCollector", "LineBotMessageCollector\LineBotMessageCollector.csproj", "{A608E508-CD67-4349-BEE7-AC287C38D665}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {241125A3-1CAA-4E48-90EF-EB5C02B02B60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {241125A3-1CAA-4E48-90EF-EB5C02B02B60}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {241125A3-1CAA-4E48-90EF-EB5C02B02B60}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {241125A3-1CAA-4E48-90EF-EB5C02B02B60}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {E85C7C31-FA78-4B5A-AF31-1B4B54AE302B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {E85C7C31-FA78-4B5A-AF31-1B4B54AE302B}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {E85C7C31-FA78-4B5A-AF31-1B4B54AE302B}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {E85C7C31-FA78-4B5A-AF31-1B4B54AE302B}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {0A36C39F-9CCC-4180-A23B-8F38BE4F17C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {0A36C39F-9CCC-4180-A23B-8F38BE4F17C6}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {0A36C39F-9CCC-4180-A23B-8F38BE4F17C6}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {0A36C39F-9CCC-4180-A23B-8F38BE4F17C6}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {FC0CDDFD-EBD1-489C-826A-B3261931EAE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {FC0CDDFD-EBD1-489C-826A-B3261931EAE7}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {FC0CDDFD-EBD1-489C-826A-B3261931EAE7}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {FC0CDDFD-EBD1-489C-826A-B3261931EAE7}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {A608E508-CD67-4349-BEE7-AC287C38D665}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {A608E508-CD67-4349-BEE7-AC287C38D665}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {A608E508-CD67-4349-BEE7-AC287C38D665}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {A608E508-CD67-4349-BEE7-AC287C38D665}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {039BCE0D-5626-42F5-955B-950B6CC1B819} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /LineSearchDotNetCoreFxRepoBot/Functions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using LineBotNet.Core.GitHubApi; 7 | using LineMessaging; 8 | using Microsoft.Azure.WebJobs; 9 | using Newtonsoft.Json; 10 | 11 | namespace LineSearchDotNetCoreFxRepoBot 12 | { 13 | public class Functions 14 | { 15 | private static readonly LineOAuthClient oAuthClient = 16 | new LineOAuthClient(ConfigurationManager.AppSettings["ChannelId"], ConfigurationManager.AppSettings["ChannelSecret"]); 17 | 18 | private static LineOAuthTokenResponse tokenResponse; 19 | 20 | public static async Task ProcessQueueMessage([QueueTrigger("line-bot-workitems")] string message, TextWriter log) 21 | { 22 | log.WriteLine(message); 23 | 24 | var data = JsonConvert.DeserializeObject(message); 25 | 26 | if (data?.Events != null) 27 | { 28 | foreach (var webhookEvent in data.Events) 29 | { 30 | log.WriteLine("event type: " + webhookEvent.Type); 31 | switch (webhookEvent.Type) 32 | { 33 | case WebhookRequestEventType.Message: 34 | if (webhookEvent.Message.Type == MessageType.Text) 35 | { 36 | log.WriteLine("text: " + webhookEvent.Message.Text); 37 | 38 | if (tokenResponse == null || tokenResponse.ExpiresIn < DateTime.Now.AddDays(-1)) 39 | { 40 | tokenResponse = await oAuthClient.GetAccessToken(); 41 | } 42 | 43 | var client = new LineMessagingClient(tokenResponse.AccessToken); 44 | 45 | var result = await new GitHubSearchApi(log).Search(webhookEvent.Message.Text); 46 | if (result == null || !result.Any()) 47 | { 48 | await client.PushMessage(webhookEvent.Source.UserId, "There is no content."); 49 | return; 50 | } 51 | 52 | foreach (var s in result.Where(x => !string.IsNullOrEmpty(x))) 53 | { 54 | if (s.Length > 1024) 55 | { 56 | await client.PushMessage(webhookEvent.Source.UserId, s.Substring(0, 1024)); 57 | } 58 | else 59 | { 60 | await client.PushMessage(webhookEvent.Source.UserId, s); 61 | } 62 | } 63 | } 64 | break; 65 | 66 | default: 67 | log.WriteLine("Not implemented event type: " + webhookEvent.Type); 68 | break; 69 | } 70 | } 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /LineSearchDotNetCoreFxRepoBot/LineSearchDotNetCoreFxRepoBot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /LineSearchDotNetCoreFxRepoBot/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using Microsoft.Extensions.Logging; 3 | using System.Threading.Tasks; 4 | 5 | namespace LineBotMessageWebJob 6 | { 7 | class Program 8 | { 9 | static async Task Main() 10 | { 11 | var builder = new HostBuilder(); 12 | builder.ConfigureWebJobs(b => 13 | { 14 | b.AddAzureStorageCoreServices(); 15 | b.AddAzureStorageBlobs(); 16 | b.AddAzureStorageQueues(); 17 | }); 18 | var host = builder.Build(); 19 | using (host) 20 | { 21 | await host.RunAsync(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LineSearchDotNetCoreFxRepoBot/README.md: -------------------------------------------------------------------------------- 1 | ## Deploy LineSearchDotNetCoreFxRepoBot to Azure WebJobs 2 | 3 | Publish this project as WebJob to your WebApps 4 | 5 | Edit your WebApp App settings like a following 6 | 7 | ![App settings](https://raw.githubusercontent.com/kiyoaki/LineBotNet/master/Images/LineSearchDotNetCoreFxRepoBot.PNG "App settings") 8 | 9 | | key | value | 10 | | ------------------------------------- | ----------------------------------------------------------------------------------------------------- | 11 | | LineChannelId | Channel ID ([LINE Channels Basic information](https://business.line.me/services/)) | 12 | | LineChannelSecret | Channel Secret ([LINE Channels Basic information](https://business.line.me/services/)) | 13 | | LineTrustedUserWithAcl | MID ([LINE Channels Basic information](https://business.line.me/services/)) | 14 | | GitHubAccessToken | Access Token ([GitHub personal access tokens](https://github.com/settings/tokens)) | 15 | 16 | [How to generate GitHub API access token](https://github.com/blog/1509-personal-api-tokens "How to generate GitHub API access token") 17 | 18 | Add your WebJob global IP address to yout LINE Channels Server IP Whitelist 19 | 20 | If LINE Channels Server IP Whitelist has setting error, LINE Sending messages API response status code is 403 and content is like a following. 21 | 22 | ```javascript 23 | {"statusCode":"427","statusMessage":"Your ip address [XXX.XXX.XXX.XXX] is not allowed to access this API."} 24 | -------------------------------------------------------------------------------- /LineTranslateBot/Functions.cs: -------------------------------------------------------------------------------- 1 | using LineBotNet.Core; 2 | using LineMessaging; 3 | using Microsoft.Azure.WebJobs; 4 | using Newtonsoft.Json; 5 | using System; 6 | using System.Configuration; 7 | using System.IO; 8 | using System.Threading.Tasks; 9 | 10 | namespace LineTranslateBot 11 | { 12 | public class Functions 13 | { 14 | private static readonly LineOAuthClient oAuthClient = 15 | new LineOAuthClient(ConfigurationManager.AppSettings["ChannelId"], ConfigurationManager.AppSettings["ChannelSecret"]); 16 | 17 | private static LineOAuthTokenResponse tokenResponse; 18 | 19 | public static async Task ProcessQueueMessage([QueueTrigger("line-bot-workitems")] string message, TextWriter log) 20 | { 21 | log.WriteLine(message); 22 | 23 | var data = JsonConvert.DeserializeObject(message); 24 | 25 | if (data?.Events != null) 26 | { 27 | foreach (var webhookEvent in data.Events) 28 | { 29 | log.WriteLine("event type: " + webhookEvent.Type); 30 | switch (webhookEvent.Type) 31 | { 32 | case WebhookRequestEventType.Message: 33 | if (webhookEvent.Message.Type == MessageType.Text) 34 | { 35 | log.WriteLine("text: " + webhookEvent.Message.Text); 36 | 37 | if (tokenResponse == null || tokenResponse.ExpiresIn < DateTime.Now.AddDays(-1)) 38 | { 39 | tokenResponse = await oAuthClient.GetAccessToken(); 40 | } 41 | 42 | var client = new LineMessagingClient(tokenResponse.AccessToken); 43 | 44 | var translateApi = new TranslateApi(); 45 | var translated = translateApi.Translate(webhookEvent.Message.Text); 46 | if (string.IsNullOrEmpty(translated)) 47 | { 48 | throw new ApplicationException("reply message is empty"); 49 | } 50 | 51 | await client.PushMessage(webhookEvent.Source.UserId, translated); 52 | } 53 | break; 54 | 55 | default: 56 | log.WriteLine("Not implemented event type: " + webhookEvent.Type); 57 | break; 58 | } 59 | } 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /LineTranslateBot/LineTranslateBot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /LineTranslateBot/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using Microsoft.Extensions.Logging; 3 | using System.Threading.Tasks; 4 | 5 | namespace LineBotMessageWebJob 6 | { 7 | class Program 8 | { 9 | static async Task Main() 10 | { 11 | var builder = new HostBuilder(); 12 | builder.ConfigureWebJobs(b => 13 | { 14 | b.AddAzureStorageCoreServices(); 15 | b.AddAzureStorageBlobs(); 16 | b.AddAzureStorageQueues(); 17 | }); 18 | var host = builder.Build(); 19 | using (host) 20 | { 21 | await host.RunAsync(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LineTranslateBot/README.md: -------------------------------------------------------------------------------- 1 | ## Deploy LineTranslateBot to Azure WebJobs 2 | 3 | Publish this project as WebJob to your WebApps 4 | 5 | Edit your WebApp App settings like a following 6 | 7 | ![App settings](https://raw.githubusercontent.com/kiyoaki/LineBotNet/master/Images/WebJobSettingsForTranslateBot.PNG "App settings") 8 | 9 | | key | value | 10 | | ------------------------------------- | ----------------------------------------------------------------------------------------------------- | 11 | | LineChannelId | Channel ID ([LINE Channels Basic information](https://business.line.me/services/)) | 12 | | LineChannelSecret | Channel Secret ([LINE Channels Basic information](https://business.line.me/services/)) | 13 | | LineTrustedUserWithAcl | MID ([LINE Channels Basic information](https://business.line.me/services/)) | 14 | | MsTranslateApiClientId | Client ID ([Azure Marketplace applications](https://datamarket.azure.com/developer/applications)) | 15 | | MsTranslateApiClientSecret | Client Secret ([Azure Marketplace applications](https://datamarket.azure.com/developer/applications)) | 16 | 17 | [Getting started using the Translator API](https://www.microsoft.com/en-us/translator/getstarted.aspx "Getting started using the Translator API") 18 | 19 | Add your WebJob global IP address to yout LINE Channels Server IP Whitelist 20 | 21 | If LINE Channels Server IP Whitelist has setting error, LINE Sending messages API response status code is 403 and content is like a following. 22 | 23 | ```javascript 24 | {"statusCode":"427","statusMessage":"Your ip address [XXX.XXX.XXX.XXX] is not allowed to access this API."} 25 | ``` 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Create LINE Developers Account 2 | 3 | [LINE Developers](https://developers.line.me/ "LINE Developers") 4 | 5 | ## Deploy MessageCollector to Azure Functions 6 | 7 | Copy following C# script to your Function 8 | 9 | [run.csx](https://github.com/kiyoaki/LineBotNet/blob/master/LineBotMessageCollector/run.csx "run.csx") 10 | 11 | Edit following part in Azure Function App Settings. 12 | 13 | ![Azure Function App Settings](https://raw.githubusercontent.com/kiyoaki/LineBotNet/master/Images/ChannelSecret.PNG "Azure Function App Settings") 14 | 15 | Edit your Function Integrate Settings to output Azure Storage queue 16 | 17 | ![Azure Function Integrate Settings](https://raw.githubusercontent.com/kiyoaki/LineBotNet/master/Images/AzureFunctionsIntegrateSettings.PNG "Azure Function Integrate Settings") 18 | 19 | ## Deploy MessageSender to Azure WebJobs 20 | 21 | Publish [LineBotMessageWebJob Project](https://github.com/kiyoaki/LineBotNet/tree/master/LineBotMessageWebJob "LineBotMessageWebJob Project") as WebJob to your WebApps 22 | 23 | You can confirm this response content in WebJob console. 24 | --------------------------------------------------------------------------------