Foray-Data-Collection/webhook.php

75 lines
2.2 KiB
PHP

<?php
$bot_api = require('api_key.php');
// Send html back to the sender.
function send_html($post_message, $reply=false) {
global $decoded;
global $bot_api;
global $chat_id;
$url = 'https://api.telegram.org/bot' . $bot_api . '/sendMessage';
$post_msg = array('chat_id' => $chat_id, 'text' =>$post_message, 'parse_mode' => 'html');
if ($reply != false) {
if ($reply === true){
$post_msg['reply_to_message_id'] = $decoded->{'message'}->{'message_id'};
}
else {
$post_msg['reply_to_message_id'] = $reply;
}
}
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($post_msg)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
}
function add_to_db($success) {
global $decoded;
$user_id = $decoded->{"message"}->{"from"}->{"id"};
$timestamp = $decoded->{"message"}->{"forward_date"};
$mysql = require('mysql_credentials.php');
$conn = new mysqli($mysql['servername'], $mysql['username'], $mysql['password'], $mysql['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO data (id, timestamp, success) VALUES (?,?,?);");
$stmt->bind_param('iii', $user_id, $timestamp, $success);
$stmt->execute();
$conn->close();
}
// Get JSON from post, store it and decode it.
$var = file_get_contents('php://input');
$decoded = json_decode($var);
// Store the chat ID
$chat_id = $decoded->{"message"}->{"chat"}->{"id"};
if (!isset($decoded->{"message"}->{"forward_from"})){
exit();
}
if ($decoded->{"message"}->{"forward_from"}->{"username"} != "chtwrsbot") {
exit();
}
if (!isset($decoded->{"message"}->{"text"})){
exit();
}
$text = $decoded->{"message"}->{"text"};
if (substr_count($text, " was completely clueless. Village was successfully pillaged. You feel pleased about yourself.") == 1){
add_to_db(1);
}
elseif (substr_count($text, "noticed you and nearly beat you to death.") == 1){
add_to_db(0);
}
elseif (substr_count($text, "tried stopping you, but you were stronger.") == 1){
add_to_db(0);
}
?>