porting for docker image

this code is hell
This commit is contained in:
giomba 2020-12-05 19:28:53 +01:00
parent cb0b224594
commit a710ce6718
7 changed files with 225 additions and 227 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
config.php

3
README
View File

@ -1,3 +0,0 @@
Further info (in Italian) at
http://golem.linux.it/wiki/GOLEM_Telegram_Bot

8
README.md Normal file
View File

@ -0,0 +1,8 @@
# golem-telegram-bot
http://golem.linux.it/wiki/GOLEM_Telegram_Bot
## sqlite3 database creation
```
CREATE TABLE telegram_post (ID INTEGER PRIMARY KEY NOT NULL, MessageID INTEGER NOT NULL, ChatID INTEGER NOT NULL, DateTime DATETIME NOT NULL, Text TEXT NOT NULL, Author TEXT);
```

View File

@ -3,13 +3,11 @@
/* Telegram API URL - this must not be changed */
const API_URL = 'https://api.telegram.org/bot';
/* Your API authorization token */
const API_TOKEN = '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw';
const API_TOKEN = '';
/* Your channel ID */
const API_CHANNEL_ID = '@';
/* Users whose messages are forwarded to mailing list and channel */
const BOT_ALLOWED_USERS = array ();
/* Users who can use the new bot interface */
const BOT_BETA_TESTERS = array ();
/* Address to forward to */
const MAIL_TO_ADDR = 'example@example.com';
/* Bot email identity */
@ -20,13 +18,11 @@
const FORWARD_SILENT = true;
/* Log file name */
const LOGFILE = 'botlog.log';
/* MySQL informations */
const MYSQL_USER = '';
const MYSQL_PASSWORD = '';
const MYSQL_DB = '';
const MYSQL_TABLE = '';
/* Memcached local server port */
/* Database settings */
const DBFILE = '/data/database.sqlite3';
/* Memcached server connection */
const MEMCACHED_PORT = '11211';
const MEMCACHED_HOST = 'memcached';
$EMOJI_THUMBSUP = mb_convert_encoding('👍', 'UTF-8', 'HTML-ENTITIES');
$EMOJI_THUMBSDOWN = mb_convert_encoding('👎', 'UTF-8', 'HTML-ENTITIES');

View File

@ -1,30 +1,29 @@
<?php
/*
* Codice beta v0.99.1 del GOLEMbot - 28 set 2017
* codice schifo del GOLEMbot - dal 28 set 2017
*
* Opera by giomba, lucam e giuliof released by GPLv3 license
* Opera by giomba, lucam e giuliof released under GPLv3 license
*
*/
// male, dovrebbero adeguarsi al sistema internazionale
require_once('config.php');
require_once('shared.php');
// === BEGIN ===
if (DEBUG) botlog("\n\n\n".'[II] BOT request starting at ' . date('Y-m-d H:i:s') . ' ====================' . "\n\n");
DEBUG and botlog('[II] BOT request starting at ' . date('Y-m-d H:i:s'));
$json = file_get_contents('php://input');
$row = json_decode($json);
if (DEBUG) botlog("[LOG] ".$json."\n");
DEBUG and botlog("[II] Incoming JSON ".$json."\n");
// Start up Memcached
$mc = new Memcached();
$mc->addServer('localhost', MEMCACHED_PORT)
or error("Something is wrong connecting to memcached daemon");
if ($mc == null) error('no memcached object instance');
if (! $mc->addServer(MEMCACHED_HOST, MEMCACHED_PORT)) {
error("something is wrong connecting to memcached daemon");
}
// Structure of managed telegram messages
/*
@ -58,19 +57,20 @@ $mc->addServer('localhost', MEMCACHED_PORT)
// HANDLE A CALLBACK
if (isset ($row->callback_query)) {
DEBUG and botlog('handle callback query');
$chatID = $row->callback_query->message->chat->id;
// Check if it was thrown by admitted users
in_array($row->callback_query->message->chat->username, BOT_BETA_TESTERS) or not_authorized($chatID);
in_array($row->callback_query->message->chat->username, BOT_ALLOWED_USERS) or not_authorized($chatID);
botlog('Ok authorized user pass!');
// Answer to the callback query (remove the loading sign)
if (DEBUG) info("Callback Query, answering");
info("Callback Query, answering");
$url = API_URL.API_TOKEN."/answerCallbackQuery?callback_query_id=".$row->callback_query->id;
file_get_contents($url);
// Do something - insert here useful variables
$callback_data = $row->callback_query->data;
//$callback_id = $row->callback_query->id;
$inlineID = $row->callback_query->message->message_id;
$inlineID_old = $mc->get($chatID.MC_INLINE_ID);
@ -102,10 +102,10 @@ if (isset ($row->callback_query)) {
case MSG_DELETE:
// remove current message
$sql = new mysqli('localhost', MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
$sql = new Sqlite3(DBFILE);
$IDdelete = $mc->get($chatID.MC_DELETE_SCHEDULED_ID) or error("No ID to delete");
$sql->query("DELETE FROM ".MYSQL_TABLE." WHERE ID=$IDdelete")
or error("Can't make the query, SQL error ".$sql->error);
$sql->query("DELETE FROM telegram_post WHERE ID=$IDdelete")
or error("Can't make the query, SQL error ".$sql->lastErrorMsg());
$sql->close();
@ -190,7 +190,8 @@ if (isset ($row->callback_query)) {
case MSG_SCHEDULE:
// == from here can be put in a function ==
$status = $mc->replace($chatID.MC_STATUS, STATE_WAIT_DATE) or die();
info('status MSG_SCHEDULE');
$status = $mc->replace($chatID.MC_STATUS, STATE_WAIT_DATE) or error(__FILE__ . __LINE__);
$currentTab = array(
'month' => date('n'),
'year' => date('Y'),
@ -198,8 +199,9 @@ if (isset ($row->callback_query)) {
);
$reply = getCalendarTab($currentTab['month'], $currentTab['year']);
info('calendar tab: ' . $reply);
$mc->set($chatID.MC_DATE_MSG, $currentTab) or $mc->replace($chatID.MC_DATE_MSG, $currentTab) or die ();
$mc->set($chatID.MC_DATE_MSG, $currentTab) or $mc->replace($chatID.MC_DATE_MSG, $currentTab) or error(__FILE__ . __LINE__);
$text="Quando vuoi inviare il messaggio?";
editMessageText($chatID, $inlineID, $text, "HTML", false, $reply);
@ -344,37 +346,36 @@ if (isset ($row->callback_query)) {
$text = htmlspecialchars($msg->message->text);
$dateObj = DateTime::createFromFormat('Y-n-j-G', $currentTab['year'] . '-' . $currentTab['month'] . '-' . $currentTab['day'] . '-' . $callback_data);
$formattedDate = $dateObj->format('Y-m-d H:i:s');
// add to database (mysql)
$sql = new mysqli('localhost', MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
$sql = new SQLite3(DBFILE);
// Build up mysql query
$value = "(";
$value .= $msg->message->message_id;
$value .= ",";
$value .= $msg->message->chat->id;
$value .= ",";
$value .= "'".$currentTab['year'].'-';
$value .= $currentTab['month'].'-';
$value .= $currentTab['day'].' ';
$value .= $callback_data.":00:00'";
$value .= "'$formattedDate'";
$value .= ",";
if (isset($text))
$value .= "'".$sql->escape_string($text)."'";
$value .= "'".$sql->escapeString($text)."'";
else
$value .= "''";
$value .= ",";
if (isset($msg->message->forward_from->username))
$value .= "'".$sql->escape_string($msg->message->forward_from->username)."'";
$value .= "'".$sql->escapeString($msg->message->forward_from->username)."'";
elseif (isset($msg->message->from->username))
$value .= "'".$sql->escape_string($msg->message->from->username)."'";
$value .= "'".$sql->escapeString($msg->message->from->username)."'";
else
$value .= "''";
$value .= ");";
info("Saving post in ".MYSQL_TABLE.", scheduled date: ".$value);
$query = $sql->query("INSERT INTO ".MYSQL_TABLE." (MessageID,ChatID,DateTime,Text,Author) VALUE ".$value)
or error("Can't make the query, SQL error ".$sql->error);
$query = "INSERT INTO telegram_post (MessageID,ChatID,DateTime,Text,Author) VALUES ".$value;
info('saving post in database, query: ' . $query);
$sql->query($query) or error("Can't make the query, SQL error ".$sql->lastErrorMsg());
$sql->close();
$text = "Programmazione avvenuta con successo";
@ -391,14 +392,12 @@ if (isset ($row->callback_query)) {
// HANDLE A COMMON MESSAGE (text/commands/photos...)
elseif (isset($row->message)) {
info('handling common message');
// Load variables
$chatID = $row->message->chat->id;
// Check if it was thrown by admitted users
if (in_array($row->message->from->username, BOT_ALLOWED_USERS)) {
info( ' Telegram: forwarding to channel... ');
forwardMessage(API_CHANNEL_ID, $row->message->chat->id, $row->message->message_id, FORWARD_SILENT);
}
else if (in_array($row->message->from->username, BOT_BETA_TESTERS)) {
if (in_array($row->message->from->username, BOT_ALLOWED_USERS)) {
info('authorized user ok');
// Finally, check actual state and do things
$status = $mc->get($chatID.MC_STATUS);
@ -406,7 +405,7 @@ elseif (isset($row->message)) {
$mc->set($chatID.MC_STATUS, STATE_IDLE) or die(); // set status or force it to STATE_IDLE
$status = STATE_IDLE;
}
if (DEBUG) info("Starting from status $status");
info("Starting from status $status");
// Reset CMD
if (($command = getCommand($row->message))['command'] == '/reset') {

View File

@ -8,17 +8,16 @@ require_once('shared.php');
if (DEBUG) botlog("\n\n\n".'[II] Scheduler starting at ' . date('Y-m-d H:i:s') . ' ====================' . "\n\n");
// Get current date in MySQL DATETIME default format
$dateID = date('Y-n-d G:00');
// Get current date in sqlite datetime format
$dateID = date('Y-m-d H:i:s');
// Connect to MySQL DB
$sql = new mysqli('localhost', MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
$query = $sql->query("SELECT MessageID,ChatID,DateTime,Text,Author FROM ".MYSQL_TABLE.
" WHERE DateTime<='".$dateID."'")
$sql = new Sqlite3(DBFILE);
$query = $sql->query("SELECT MessageID,ChatID,DateTime,Text,Author FROM telegram_post WHERE DateTime<='".$dateID."'")
or error("Can't make the query, SQL error ".$sql->error);
// Post all messages (only text)
while ($row = $query->fetch_assoc()) {
while ($row = $query->fetchArray()) {
info("Publishing message $row[MessageID]");
/*
$bot_query = API_URL . API_TOKEN . '/sendMessage?' .
@ -32,7 +31,7 @@ while ($row = $query->fetch_assoc()) {
}
// Remove just posted messages (and any eventual previous one)
$sql->query("DELETE FROM ".MYSQL_TABLE." WHERE DateTime<='".$dateID."'");
// Remove just posted messages (and possibly any previous one)
$sql->query("DELETE FROM telegram_post WHERE DateTime<='".$dateID."'");
$sql->close();
?>

View File

@ -1,29 +1,27 @@
<?php
require_once('config.php');
// Base logging function. All logging functions use this.
// Change this to output everything on stdout, on file, on socket, on whathever you want...
function botlog($info) {
if ($file = fopen(LOGFILE, 'a'))
{
fwrite($file, $info);
fclose($file);
}
error_log($info);
}
// Unrecoverable error, program must be terminated
function error($message) {
if (DEBUG) botlog("[EE] $message\n");
if (DEBUG) botlog('[II] BOT request (cruently) ended at ' . date('Y-m-d H:i:s') . ' ====================' . "\n");
if (DEBUG) botlog("[EE] $message");
if (DEBUG) botlog('[II] BOT request died');
die();
}
// Uncommon event
function warning($message) {
if (DEBUG) botlog("[WW] $message\n");
if (DEBUG) botlog("[WW] $message");
}
// Routine debugging informations
function info($message) {
if (DEBUG) botlog("[II] $message\n");
if (DEBUG) botlog("[II] $message");
}
// Interpreta un comando inviato al bot - mettere null o simili invece di -1
@ -105,6 +103,7 @@
$answer = file_get_contents($query);
if ($answer === false) warning("Something is wrong in editMessageText - chat_id: $chat_id - message_id: $message_id");
info("edit message answer: $answer");
return $answer;
}
@ -140,6 +139,7 @@
// Makes the calendar inline keyboard
function getCalendarTab ($month, $year) {
info('getting calendar...');
$kbd = new InlineKbd;
$days = array("L", "M", "M", "G", "V", "S", "D");
@ -152,7 +152,7 @@
$date = $year."-".$month;
$isCurrentMonth = date('nY') == $month.$year;
$startingDay = $isCurrentMonth ? date('j') : 1;
if (DEBUG) botlog("[II] First day: ".$date.'-'.$startingDay."\n");
info("[II] First day: ".$date.'-'.$startingDay."\n");
$firstDay = date("N", strtotime($date.'-'.$startingDay));
// blank buttons
@ -194,9 +194,9 @@
// -- I dont' like so much --
function navigateMsgArchive ($msgNumber, $mc, $chatID) {
$sql = new mysqli('localhost', MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
$numbers = $sql->query("SELECT COUNT(*) FROM ".MYSQL_TABLE);
$numbers = $numbers->fetch_array()[0];
$sql = new Sqlite3(DBFILE);
$numbers = $sql->query("SELECT COUNT(*) FROM telegram_post");
$numbers = $numbers->fetchArray()[0];
if ($numbers == 0) {
return array( "text" => "Nessun messaggio programmato",
"kbd" => null);
@ -207,11 +207,9 @@
//~ die();
}
else {
$query = $sql->query("SELECT DATE_FORMAT(DateTime,'%d/%m/%Y ore %H') as DateTimeFormat,ChatID, MessageID,Text,Author,ID FROM ".MYSQL_TABLE."
ORDER BY DateTime ASC LIMIT 1 OFFSET $msgNumber") or error("Can't make the query, SQL error ".$sql->error);
$query = $sql->query("SELECT DateTime as DateTimeFormat,ChatID, MessageID,Text,Author,ID FROM telegram_post ORDER BY DateTime ASC LIMIT 1 OFFSET $msgNumber") or error("Can't make the query, SQL error ".$sql->error);
//while($row = $query->fetch_assoc()) {
$row = $query->fetch_assoc();
$row = $query->fetchArray();
$mc->set($chatID.MC_DELETE_SCHEDULED_ID, $row['ID'])
or $mc->replace($chatID.MC_DELETE_SCHEDULED_ID, $row['ID']);
@ -248,7 +246,7 @@
function not_authorized($chatID) {
$query = API_URL . API_TOKEN . '/sendMessage?' .
'chat_id=' . urlencode($chatID) .
"&text=".urlencode("Utente non autorizzato\nhttps://www.youtube.com/watch?v=HO8ctP_QNZc");
"&text=".urlencode("Questo bot è solo per il Consiglio Direttivo.\nForse cercavi @golem_empoli (canale) oppure https://golem.linux.it/ (sito)");
file_get_contents($query);