witnessmenow / Universal-Arduino-Telegram-Bot

Use Telegram on your Arduino (ESP8266 or Wifi-101 boards)
MIT License
1.09k stars 302 forks source link

[Solved] - Bot token as variable from spiffs, possible? #265

Closed do8pgg closed 2 years ago

do8pgg commented 2 years ago

Is it possible to take the bot token as a variable from the spiffs? In principle I can read the token and also display it e.g. as Serial.print(spiffs_token); display it. But

UniversalTelegramBot(BOT_TOKEN, client).sendMessage(chat_id, welcome, "");

does not work like this. Anyone have any idea how to do this? Would hate to have the token hard in the code.

here my Test-Code;

// Testversion 30.11.2021 - 11:22

//Libraries

include

include

include

include

include

FS& gfs = LittleFS; eSPIFFS fileSystem;

//WiFi Credentials const char ssid = "AP"; const char password = "**";

//Initialize Telegram-Bot // #define botToken "1234567890:1234blah5678foo"

//Your UserID // #define userID "123456789"

WiFiClientSecure client;

int numNewRequests; String text = ""; String chat_id = ""; String from_name = ""; String welcome = ""; String BOT_TOKEN;

void handleNewRequests(int numNewRequests) { fileSystem.openFromFile("/token.txt", BOT_TOKEN); Serial.println("im newRequest"); for (int i = 0; i < numNewRequests; i++) { //loops through new requests chat_id = String(UniversalTelegramBot(BOT_TOKEN, client).messages[i].chat_id); from_name = UniversalTelegramBot(BOT_TOKEN, client).messages[i].from_name; if (text == "/start") { welcome = "Willkommen, " + from_name + ".\n"; UniversalTelegramBot(BOT_TOKEN, client).sendMessage(chat_id, welcome, ""); } } }

void Wifi () { Serial.print("Connecting to: "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(300); } Serial.println(""); Serial.println("Verbunden!"); }

void setup() { Serial.begin(115200); Wifi(); fileSystem.openFromFile("/token.txt", BOT_TOKEN); }

void loop() { int numNewRequests = UniversalTelegramBot(BOT_TOKEN, client).getUpdates(UniversalTelegramBot(BOT_TOKEN, client).last_message_received + 1); Serial.println("loop vor while\n "); while (numNewRequests) { Serial.println("im while\n "); handleNewRequests(numNewRequests); numNewRequests = UniversalTelegramBot(BOT_TOKEN, client).getUpdates(UniversalTelegramBot(BOT_TOKEN, client).last_message_received + 1); } delay(1000);

witnessmenow commented 2 years ago

Yeah it is possible.

do8pgg commented 2 years ago

Thank you very much, this works perfectly! Now to solve my favorite problem; 'if else etc' for more than one user. But I will manage that :-)

// ChatID test
if (chat_id != Peter) {
  bot.sendMessage(chat_id, "Nope!", "");
  continue;
}
// ChatID test

Best regards, Peter