Created
April 5, 2020 08:42
-
-
Save cirnatdan/7d8cb26759f349579995c2703bbc1996 to your computer and use it in GitHub Desktop.
Telegram bot in D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
import std.string; | |
import requests; | |
import std.json; | |
import std.typecons: tuple, Tuple; | |
import std.conv; | |
import std.process; | |
string URL = ""; | |
enum SLEEP = false; | |
string getUrl(string url) | |
{ | |
return getContent(url).toString(); | |
} | |
auto getJsonFromUrl(string url) | |
{ | |
return parseJSON(getUrl(url)); | |
} | |
auto getUpdates(long lastUpdateId) | |
{ | |
string url = URL ~ "getUpdates?timeout=10"; | |
if (-1 != lastUpdateId) { | |
url = url ~ "&offset=" ~ to!string(lastUpdateId); | |
} | |
return getJsonFromUrl(url); | |
} | |
auto getLastChatIdAndText(JSONValue updates) | |
{ | |
updates.writeln; | |
auto lastUpdate = updates["result"].array.length - 1; | |
if ("group_chat_created" in updates["result"][lastUpdate]["message"]) { | |
return tuple("", -1L); | |
} | |
auto text = updates["result"][lastUpdate]["message"]["text"].str; | |
auto chat_id = updates["result"][lastUpdate]["message"]["chat"]["id"].integer; | |
return tuple(text, chat_id); | |
} | |
auto sendMessage(string text, long chat_id) | |
{ | |
string url = URL ~ "sendMessage?text=%s&chat_id=%s".format(text, chat_id); | |
getUrl(url); | |
} | |
void respond(JSONValue update) | |
{ | |
if ("message" !in update) return; | |
auto chatId = update["message"]["chat"]["id"].integer; | |
switch(update["message"]["from"]["first_name"].str) { | |
case "Dan": | |
sendMessage("Good day to you!", chatId); | |
return; | |
default: | |
if (SLEEP) { | |
sendMessage("I am sleeping, leave me alone", chatId); | |
return; | |
} else { | |
sendMessage("Hey there", chatId); | |
return; | |
} | |
} | |
} | |
void main() | |
{ | |
string TOKEN = environment.get("TOKEN"); | |
URL = "https://api.telegram.org/bot%s/".format(TOKEN); | |
long lastUpdateId = -1; | |
while (true) { | |
auto updates = getUpdates(lastUpdateId); | |
if ("result" !in updates) { | |
continue; | |
} | |
JSONValue result = updates["result"]; | |
foreach (update; result.array) { | |
update.writeln; | |
lastUpdateId = update["update_id"].integer + 1; | |
respond(update); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment