Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

170
LINES

< > BotCompany Repo | #1017517 // Telegram Bot + wit.ai speech recognition (Logs & Posts From Log)

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Uses 33700K of libraries. Click here for Pure Java version (21691L/135K).

1  
!7
2  
3  
!include once #1017511 // Telegram Bots
4  
5  
import org.telegram.telegrambots.generics.BotSession;
6  
import org.telegram.telegrambots.api.objects.inlinequery.InlineQuery;
7  
import org.telegram.telegrambots.api.methods.*;
8  
import org.telegram.telegrambots.api.objects.inlinequery.result.*;
9  
import org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent.*;
10  
11  
static TelegramLongPollingBot bot;
12  
static BotSession botSession;
13  
14  
sbool useWitAI = true; // only on Linux (but that can be changed) & when you have a token
15  
16  
p {
17  
  fS apiToken = telegramBotToken_mandatory();
18  
19  
  ApiContextInitializer.init();
20  
  bot = new TelegramLongPollingBot {
21  
    public S getBotUsername() { ret "HelloComputer_bot"; }
22  
    public S getBotToken() { ret apiToken; }
23  
    
24  
    public void onUpdateReceived(Update update) {
25  
      pcall {
26  
        print("Got update! " + update);
27  
        
28  
        InlineQuery iq = update.getInlineQuery();
29  
        if (iq != null) {
30  
          answerInlineQuery(new AnswerInlineQuery()
31  
            .setInlineQueryId(iq.getId())
32  
            .setResults(new InlineQueryResultArticle()
33  
              .setId(aGlobalID())
34  
              .setTitle("Title.")
35  
              .setDescription("Description.")
36  
              .setInputMessageContent(
37  
                new InputTextMessageContent()
38  
                  .setMessageText("Hello there. You said: " + iq.getQuery()))));
39  
        }
40  
        
41  
        Message msg = update.getMessage(); //update.getChannelPost();
42  
        logQuotedWithDate(telegramFullUpdatesLogFile(), str(update));
43  
        if (msg == null) ret;
44  
        final Chat chat = msg.getChat();
45  
        final User from = msg.getFrom();
46  
        
47  
        final Map map = litorderedmap(
48  
          where := chat == null ? null : chat.getId(),
49  
          type := 'heard,
50  
          date := localDateWithMilliseconds(),
51  
          globalID := aGlobalID());
52  
53  
        Voice voice = msg.getVoice();
54  
        if (voice != null) {
55  
          Int duration = voice.getDuration();
56  
          fS mimeType = voice.getMimeType();
57  
          S fileID = voice.getFileId();
58  
          print("Incoming voice message, downloading");
59  
          printStructs(+duration, +mimeType, +fileID);
60  
          
61  
          replace TgFile with org.telegram.telegrambots.api.objects.File.
62  
          
63  
          // Download voice message
64  
          new GetFile getFileMethod;
65  
          getFileMethod.setFileId(fileID);
66  
          TgFile tgFile = execute(getFileMethod);
67  
          
68  
          downloadFileAsync(tgFile, new DownloadFileCallback<TgFile> {
69  
            public void onResult(TgFile file, java.io.File f) {
70  
              print("Got voice message: " + fileInfo(f));
71  
              // Assuming ogg
72  
              final File f2 = javaxDataDir("Stored Voice Messages/" + (from != null ? from.getId() : 0) + "-" + now() + ".ogg");
73  
              copyFileVerbose(f, f2);
74  
              if (useWitAI && nempty(witAITokenOpt())) thread "Wit.AI" {
75  
                File f3 = f2;
76  
                S _mimeType = mimeType;
77  
                if (eq(mimeType, "audio/ogg")) {
78  
                  pcall {
79  
                    oggToMP3(f2, f3 = replaceFileExtension(f2, ".mp3"));
80  
                  }
81  
                  if (fileEmpty(f3)) fail("Can't convert to mp3");
82  
                  _mimeType = "audio/mpeg3";
83  
                  printFileInfo(f3);
84  
                }
85  
86  
                fS text = witAI_recognizeAudio(f3, _mimeType);
87  
                if (nempty(text)) {
88  
                  putAll(map, litorderedmap(
89  
                    +text,
90  
                    fromVoice := true));
91  
                  logStructure(telegramLogFile(), map);
92  
                  botAppendToMechList_combining("Telegram Bot Log", struct(map));
93  
                  // Allow think bot to answer, then post what was said
94  
                  doAfter(5000, r { telegram_postToSendLog(
95  
                    "(I think you said: " + quote(text) + ")",
96  
                    chat == null ? null : chat.getId());
97  
                  });
98  
                }
99  
              }
100  
            }
101  
            
102  
            public void onException(TgFile file, Exception e) {
103  
              print("Couldn't download voice message: " + e);
104  
            }
105  
          });
106  
        }
107  
        
108  
        if (msg.hasText()) {
109  
          S text = msg.getText();
110  
          print("Incoming text: " + text);
111  
          putAll(map, litorderedmap(
112  
            originalDate := msg.getDate(),
113  
            +text));
114  
            
115  
          if (from != null)
116  
            putAll(map, litorderedmap(
117  
              userID := from.getId(),
118  
              userFirstName := from.getFirstName(),
119  
              userLastName := from.getLastName()));
120  
121  
          logStructure(telegramLogFile(), map);
122  
          botAppendToMechList_combining("Telegram Bot Log", struct(map));
123  
        }
124  
      }
125  
    }
126  
  };
127  
128  
  botSession = new TelegramBotsApi().registerBot(bot);
129  
  
130  
  watchStructureLog_future(telegramBotToSendLog(), 100, voidfunc(Map map) {
131  
    if (eq(map.get('action), 'send)) {
132  
      long chatID = or((Long) _get(map, 'where), telegram_chatID());
133  
      S globalID = or2(getString(map, 'globalID), aGlobalID());
134  
      S voice = getString(map, 'voice);
135  
      S text = getString(map, 'text);
136  
      
137  
      if (voice != null)
138  
        telegram_sendVoiceMessageWithLogging(bot, chatID, text, voice, globalID);
139  
      else
140  
        telegram_sendWithLogging(bot, chatID, text, globalID);
141  
        
142  
      putAll(map, litorderedmap(
143  
        date := localDateWithMilliseconds(),
144  
        type := 'sent,
145  
        +globalID,
146  
        +chatID));
147  
      botAppendToMechList_combining("Telegram Bot Log", struct(map));
148  
    }
149  
  });
150  
  
151  
  print("Telegram Bot running.");
152  
}
153  
154  
svoid cleanMeUp {
155  
  if (botSession != null) {
156  
    final BotSession _botSession = botSession;
157  
    botSession = null;
158  
    if (vmExiting()) {
159  
      print("Closing bot session during VM close");
160  
      // As stop() takes unusually long, don't bother waiting the whole time
161  
      joinThreadForSomeTime(startThread(r { _botSession.stop(); }), 2000);
162  
    } else {
163  
      print("Closing bot session with profiling");
164  
      temp relicense();
165  
      temp profileThisThreadToConsole();
166  
      _botSession.stop();
167  
      print("Closed bot session");
168  
    }
169  
  }
170  
}

Author comment

Began life as a copy of #1017513

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1017517
Snippet name: Telegram Bot + wit.ai speech recognition (Logs & Posts From Log)
Eternal ID of this version: #1017517/61
Text MD5: d3b1ef6480f60583d529a9eb679dd743
Transpilation MD5: 4596877b8f25cfa5655f37f58bbd364d
Author: stefan
Category: javax / networking
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-08-27 00:29:14
Source code size: 6299 bytes / 170 lines
Pitched / IR pitched: No / No
Views / Downloads: 684 / 1985
Version history: 60 change(s)
Referenced in: [show references]