-
Notifications
You must be signed in to change notification settings - Fork 0
/
TG.cs
298 lines (261 loc) · 9.85 KB
/
TG.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types.ReplyMarkups;
using System.Threading;
using System.Net;
using Newtonsoft.Json;
using System.IO;
namespace EMGU_Example
{
public class TG
{
public delegate void OnSelCameraChanged(int nIdx);
public event OnSelCameraChanged OnSelCameraChangedEvt;
public delegate void OnThresholdChanged(string nTrigger);
public event OnThresholdChanged OnThresholdChangedEvt;
private string _token, _chatId, _botprivatechatId;
private Settings _setting;
bool _bSentGroup;
TelegramBotClient _botClient;
TelegramBotClient _botClient_Listen;
CancellationTokenSource _cts;
DetectBot _form = null;
public TG(DetectBot form, Settings setting)
{
_form = form;
_setting = setting;
_token = _setting.TGtoken;
_chatId = _setting.TGchatID;
_botClient = new TelegramBotClient(_token);
_botClient_Listen = new TelegramBotClient(_token);
_cts = new CancellationTokenSource();
_botprivatechatId = getRobotPrivateChatId();
_bSentGroup = _setting.TGSendToGroup.Equals("1") ? true : false;
Handlers.msgDele = TgBot_CmdHandler;
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types
};
_botClient_Listen.StartReceiving(updateHandler: Handlers.HandleUpdateAsync,
errorHandler: Handlers.HandleErrorAsync,
receiverOptions: receiverOptions,
cancellationToken: _cts.Token);
}
public void StopTGBotReceiving()
{
_cts.Cancel();
}
public async Task<Telegram.Bot.Types.Message> SendImgAsync(string path)
{
string[] timestamp = path.Split('\\');
string targetChatId = _bSentGroup ? _chatId : _botprivatechatId;
string caption = "[" + timestamp[timestamp.Length - 1].Split('.')[0] + "] 偵測到移動!";
if (targetChatId == String.Empty)
return null;
using (var stream = System.IO.File.OpenRead(path))
{
InputOnlineFile file = new InputOnlineFile(stream);
Telegram.Bot.Types.Message msg = await _botClient.SendPhotoAsync(
chatId: targetChatId,
photo: file,
caption: caption);
return msg;
}
}
public void robotMessage(string v)
{
if (_botprivatechatId.Equals(""))
_botprivatechatId = getRobotPrivateChatId();
_botClient.SendTextMessageAsync(
chatId: _botprivatechatId,
text: v,
parseMode: ParseMode.MarkdownV2,
disableNotification: true,
cancellationToken: _cts.Token);
}
public void robotSendMenu()
{
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(new KeyboardButton[] {
"🖐HI", "📷DEVS" ,"🤔STATE","🔛ON", "❎OFF", "TRG"
});
replyKeyboardMarkup.ResizeKeyboard = true;
_botClient.SendTextMessageAsync(
chatId: _botprivatechatId,
text: "請按需求按下面按鈕😄",
replyMarkup: replyKeyboardMarkup,
disableNotification: true,
cancellationToken: _cts.Token);
}
private string getRobotPrivateChatId()
{
string chatId = "";
string API_URL = $"https://api.telegram.org/bot{_token}/getUpdates";
var request = WebRequest.Create(API_URL);
var response = (HttpWebResponse)request.GetResponse();
var myJsonResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
if(myDeserializedClass.result.Count > 0)
{
chatId = myDeserializedClass.result[0].message.from.id.ToString();
}
}
return chatId;
}
private void TgBot_CmdHandler(string sCmd)
{
if (this._form.InvokeRequired)
{
Action<string> bAct = new Action<string>(TgBot_CmdHandler);
this._form.Invoke(bAct, sCmd);
}
else
{
sCmd = sCmd.ToUpper();
if (sCmd.Contains("ON"))
{
robotMessage("開始偵測");
this._form.btnCapture_Click(null, null);
}
else if (sCmd.Contains("OFF"))
{
robotMessage("停止偵測");
this._form.btnStop_Click(null, null);
}
else if (sCmd.Contains("HI"))
{
robotMessage("HELLO 歡迎使用");
robotSendMenu();
}
else if (sCmd.Contains("DEVS"))
{
robotMessage("Camera共有: " + this._form.nCameraCount + "台, 請輸入SEL加數字\\(從0開始\\)選擇您要的裝置, 如SEL0");
}
else if (sCmd.Contains("STATE"))
{
robotMessage("偵測中: " + (this._form._IsCapturing ? "是" : "否"));
}
else if (sCmd.Contains("SEL"))
{
int selectCamera = Int32.Parse(sCmd.Replace("SEL", "").Trim());
if (selectCamera >= this._form.nCameraCount || selectCamera < 0)
{
robotMessage("❌輸入錯誤請修正");
return;
}
OnSelCameraChangedEvt(selectCamera);
robotMessage("切換Camera" + selectCamera + "成功");
}
else if (sCmd.Contains("TRG"))
{
string sThreshold = sCmd.Replace("TRG", "");
if (sThreshold.Equals(""))
{
robotMessage("目前觸發值: " + _setting.TriggerBound + " 😄設置觸發值方式👉 TRG5000");
return;
}
else
{
int nTrigger;
if (Int32.TryParse(sThreshold, out nTrigger) )
{
//No need to be changed
if ( _setting.TriggerBound == nTrigger)
return;
OnThresholdChangedEvt(sThreshold);
robotMessage("✅設置觸發值成功");
Thread.Sleep(2000);
this._form.btnApplySetting_Click(null, null);
}
else
{
robotMessage("❌輸入錯誤請修正");
}
}
}
else
{
robotMessage("Q Q 我不懂你的明白");
}
}
}
}
public class Handlers
{
public static Action<string> msgDele;
public static string robotChatId;
public static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
Console.WriteLine(exception.Message);
return Task.CompletedTask;
}
public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
Task handle;
switch (update.Type)
{
default:
case UpdateType.Message:
handle = BotOnMessageReceived(botClient, update.Message);
break;
}
await handle;
}
private static Task BotOnMessageReceived(ITelegramBotClient botClient, Message message)
{
if (message == null)
{
return Task.CompletedTask;
}
if (message.Type == MessageType.Text)
{
msgDele.Invoke(message.Text);
}
return Task.CompletedTask;
}
}
#region Transform JSON format to Class with https://json2csharp.com/
public class Chat
{
public int id { get; set; }
public string first_name { get; set; }
public string username { get; set; }
public string type { get; set; }
}
public class From
{
public int id { get; set; }
public bool is_bot { get; set; }
public string first_name { get; set; }
public string username { get; set; }
public string language_code { get; set; }
}
public class Messages
{
public int message_id { get; set; }
public From from { get; set; }
public Chat chat { get; set; }
public int date { get; set; }
public string text { get; set; }
}
public class Result
{
public int update_id { get; set; }
public Messages message { get; set; }
}
public class Root
{
public bool ok { get; set; }
public List<Result> result { get; set; }
}
#endregion
}