Advertisement
NovaYoshi

telegram echo bot

Jul 5th, 2016
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. AddonInfo <- {
  2. "Name":"Telegram bot"
  3. "Summary":"Telegram bot API"
  4. "Version":"0.01"
  5. "Author":"NovaSquirrel"
  6. };
  7.  
  8. // Calls a Telegram API function and calls a callback
  9. function DoAPI(Method, Parameters, Function, Extra) {
  10. function DoNothing(C, D, E){};
  11. const Key = "insert key here";
  12. local URL = "https://api.telegram.org/bot"+Key+"/"+Method;
  13. if(Function == null)
  14. Function = DoNothing;
  15. if(Parameters)
  16. api.CurlPost(Function, Extra, URL, api.MakeForms(Parameters));
  17. else
  18. api.CurlGet(Function, Extra, URL);
  19. }
  20.  
  21. // Telegram sends chat IDs as big integers, but Squirrel by default only has 32-bit ones
  22. // so change the integers to the strings they should have been in the first place
  23. function ChatIDFix(Text) {
  24. function isdigit(character) {
  25. return character >= '0' && character <= '9';
  26. }
  27.  
  28. local FindMe = @"""chat"":{""id"":";
  29. local FixedText = "";
  30. local CurIndex = 0;
  31.  
  32. while(1) {
  33. local FindIndex = Text.find(FindMe, CurIndex);
  34. if(FindIndex == null) {
  35. FixedText += Text.slice(CurIndex);
  36. break;
  37. }
  38. // add the text up until the found thing
  39. FixedText += Text.slice(CurIndex, FindIndex)+FindMe+"\"";
  40. CurIndex = FindIndex+FindMe.len();
  41. // add the number, and close off the quotation mark
  42. while(isdigit(Text[CurIndex]))
  43. FixedText += format("%c", Text[CurIndex++]);
  44. FixedText += "\"";
  45. }
  46.  
  47. return FixedText;
  48. }
  49.  
  50. local UpdateId = 0;
  51.  
  52. function ApiTestCmd(T, P, C) {
  53. P = api.CmdParamSplit(P);
  54.  
  55. function RequestUpdates() {
  56. if(UpdateId)
  57. DoAPI("getUpdates", {"offset":UpdateId+1, "timeout":60}, GotAnswer, null);
  58. else
  59. DoAPI("getUpdates", {"timeout":60}, GotAnswer, null);
  60. }
  61.  
  62. // Got an update
  63. function GotUpdate(Code, Data, Extra) {
  64. Data = api.DecodeJSON(ChatIDFix(Data));
  65.  
  66. foreach(Update in Data.result) {
  67. if(Update.update_id > UpdateId)
  68. UpdateId = Update.update_id;
  69. local Message = Update.message;
  70. local From = ("from" in Message)?Message.from.username:"?";
  71. local Text = ("text" in Message)?Message.text:null;
  72. if(Text) {
  73. print(From+":"+Text);
  74. DoAPI("sendMessage", {"chat_id":Message.chat.id, "text":Text}, null, null);
  75. }
  76. }
  77. RequestUpdates();
  78. }
  79. RequestUpdates();
  80. return EventReturn.HANDLED;
  81. }
  82. api.AddCommandHook("tgtest", ApiTestCmd, Priority.NORMAL, null, null);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement