Skip to content

Commit

Permalink
Implement Telegram Connect #2
Browse files Browse the repository at this point in the history
  • Loading branch information
MrKrisKrisu committed May 14, 2020
1 parent 0e90bb3 commit c85667a
Show file tree
Hide file tree
Showing 8 changed files with 207 additions and 23 deletions.
2 changes: 1 addition & 1 deletion app/Console/Commands/REWE_ParseBon.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public function handle()
$message .= count($positions) . " Produkte für " . $bon->total . "\r\n";
$message .= "Erhaltenes Cashback: " . round($bon->earned_payback_points / ($bon->total * 100) * 100, 2) . '%';

TelegramController::sendMessage(User::find($userEmail->verified_user_id), $message);
//TelegramController::sendMessage(User::find($userEmail->verified_user_id), $message);
}
} catch (\Exception $e) {
dump($e);
Expand Down
44 changes: 44 additions & 0 deletions app/Console/Commands/Telegram_SetWebhook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Console\Commands;

use App\Http\Controllers\TelegramController;
use Illuminate\Console\Command;

class TelegramSetWebhook extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'telegram:set_webhook';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Set Telegram Webhook';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$res = TelegramController::setWebhook();
echo $res ? 'Webhook set successfully.' : 'Error while create Webhook.';
}
}
2 changes: 2 additions & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Console;

use App\Console\Commands\TelegramSetWebhook;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

Expand All @@ -14,6 +15,7 @@ class Kernel extends ConsoleKernel
* @var array
*/
protected $commands = [
TelegramSetWebhook::class
];

/**
Expand Down
50 changes: 34 additions & 16 deletions app/Http/Controllers/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use App\SocialLoginProfile;
use App\UserEmail;
use App\UserSettings;
use Carbon\Carbon;
use Illuminate\Support\Facades\Request;

class SettingsController extends Controller
Expand All @@ -26,40 +28,56 @@ public function __construct()
*/
public function index()
{

$socialProfile = auth()->user()->socialProfile()->first() ?: new SocialLoginProfile;

$isConnectedToTwitter = $socialProfile->twitter_token != NULL;
$isConnectedToSpotify = $socialProfile->spotify_accessToken != NULL;
$isConnectedToTelegram = UserSettings::get(auth()->user()->id, 'telegramID', '') != '';

$telegramConnectCode = UserSettings::where('name', 'telegram_connectCode')
->where('user_id', auth()->user()->id)
->where('updated_at', '>', Carbon::now()->addHours('-1'))
->first();

$emails = UserEmail::where('verified_user_id', auth()->user()->id)->orWhere('unverified_user_id', auth()->user()->id)->get();


return view('settings', [
'isConnectedToTwitter' => $isConnectedToTwitter,
'isConnectedToSpotify' => $isConnectedToSpotify,
'isConnectedToTelegram' => $isConnectedToTelegram,
'telegramConnectCode' => $telegramConnectCode,
'emails' => $emails
]);
}

public function save(\Illuminate\Http\Request $request)
{
if (isset($request->addEmail)) {
$email = UserEmail::where('email', $request->addEmail)->first();
if ($email != NULL) {
dd("Dieser E-Mail Adresse ist bereits einem Accounts zugewiesen. Bitte wende sich an den Support.");
//TODO: Schönere Meldung
} else {
$email = UserEmail::create([
'email' => $request->addEmail,
'unverified_user_id' => auth()->user()->id,
'verification_key' => md5(rand(0, 99999) . time() . auth()->user()->id)
]);

//TODO: Email Bestätigung senden
if (isset($request->action)) {
switch ($request->action) {
case 'createTelegramToken':
$connectCode = rand(111111, 999999);
UserSettings::set(auth()->user()->id, 'telegram_connectCode', $connectCode);
return $this->index();

}

return $this->index();
case 'addEMail':
$email = UserEmail::where('email', $request->email)->first();
if ($email != NULL) {
dd("Dieser E-Mail Adresse ist bereits einem Accounts zugewiesen. Bitte wende sich an den Support.");
//TODO: Schönere Meldung
} else {
$email = UserEmail::create([
'email' => $request->email,
'unverified_user_id' => auth()->user()->id,
'verification_key' => md5(rand(0, 99999) . time() . auth()->user()->id)
]);

//TODO: Email Bestätigung senden

}
return $this->index();
}
}
}

Expand Down
94 changes: 90 additions & 4 deletions app/Http/Controllers/TelegramController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,58 @@

use App\User;
use App\UserSettings;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class TelegramController extends Controller
{
/**
* Required once to create the Webhook at Telegram API to handle Messages sent to the bot
* @return boolean
*/
public static function setWebhook()
{
$client = new Client();
$result = $client->post('https://api.telegram.org/bot' . env('TELEGRAM_TOKEN') . '/setWebhook', [
'headers' => [
'Content-type' => 'application/json'
],
'body' => json_encode([
'url' => env('APP_URL') . '/api/telegram/webhook/'
])
]);

if ($result->getStatusCode() != 200)
return false;

$data = json_decode($result->getBody()->getContents());

if ($data->ok)
return true;
return false;
}

/**
* @param User $user
* @param String $message
* @return bool
* @throws \Exception
*/
public static function sendMessage(User $user, String $message)
public static function sendMessage(User $user, string $message)
{
return true; //for development with real data...
$telegramID = UserSettings::get($user->id, 'telegram_id');

return self::sendMessageToChat($telegramID, $message);
}

/**
* @param int $telegramID
* @param String $message
* @return bool
* @throws \Exception
*/
private static function sendMessageToChat(int $telegramID, string $message)
{
if ($telegramID == NULL)
return false;

Expand All @@ -41,7 +78,56 @@ public static function sendMessage(User $user, String $message)

if (isset($data->ok) && $data->ok)
return true;
throw new Expception("There was an error while sending message.");
throw new \Exception("There was an error while sending message.");
}

/**
* Handles incoming Telegram Webhook (ex. new messages)
* Thrown by API Route
*/
public static function handleWebhook()
{
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if (!isset($update['message']['chat']['id']))
return;

$chatID = $update['message']['chat']['id'];
$username = $update['message']['chat']['username'];
$messageText = $update['message']['text'];
$commandEx = explode(' ', explode('@', $messageText)[0]);

if ($commandEx[0] == '/start') {
self::sendMessageToChat($chatID, "<b>Willkommen bei KStats!</b>\r\n"
. "Um Telegram mit KStats nutzen zu können musst du deinen Account mit Telegram verbinden.\r\n"
. "Auf der Seite 'Einstellungen' kannst du deinen Telegram-ConnectCode generieren. Bitte gebe den Befehl <i>/connect CODE</i> ein und schicke diesen ab. (Ersetze <b>CODE</b> mit deinem Code.)");
return;
}

if ($commandEx[0] == '/connect') {
if (!isset($commandEx[1])) {
self::sendMessageToChat($chatID, "Bitte gebe noch deinen Code als zweites Argument an.\r\n\r\n-> /connect CODE");
return;
}

$us = UserSettings::where('name', 'telegram_connectCode')
->where('val', $commandEx[1])
->where('updated_at', '>', Carbon::now()->addHours('-1'))
->first();
if ($us == NULL) {
self::sendMessageToChat($chatID, "Der ConnectCode ist nicht korrekt.");
return;
}

self::sendMessageToChat($chatID, "Hallo " . $us->user->username . '! Dein Account ist jetzt erfolgreich verknüpft.');

UserSettings::set($us->user->id, 'telegramID', $chatID);
UserSettings::set($us->user->id, 'telegram_connectCode', $chatID);
UserSettings::set($us->user->id, 'telegram_codeValidUntil', $chatID);
return;

}
}

}
5 changes: 5 additions & 0 deletions app/UserSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,9 @@ public static function set(int $user_id, $key, $val)
]
);
}

public function user()
{
return $this->belongsTo(User::class);
}
}
31 changes: 29 additions & 2 deletions resources/views/settings.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,33 @@
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ _('Telegram Connect') }}</h5>
<p>Die Verbindung mit Telegram ist temporär nicht verfügbar.</p>
@if($isConnectedToTelegram)
<p>Du bist bereits mit einem Telegram Chat verbunden. Selbstverständlich kannst du deinen
Account aber mit einem neuen Chat verbinden.</p>
@else
<p>Du bist aktuell mit <b>keinem</b> Telegram Chat verbunden.</p>
@endif
@if($telegramConnectCode != NULL && $telegramConnectCode->val != '')

<div style="text-align: center;">
<p style="font-size: 20px;">Dein Telegram-ConnectCode lautet
"<b>{{$telegramConnectCode->val}}</b>"
<br/><small>Code gültig
bis {{$telegramConnectCode->updated_at->addHour()->isoFormat('Do MMMM YYYY, HH:mm')}}</small>
</p>
</div>
<p>Um Telegram mit KStats nutzen zu können musst du den
<a target="tg" href="https://t.me/kstat_bot">KStats Bot</a> starten und den Anweisungen
folgen.
</p>
<small>Wenn du die Anweisungen nicht erhältst schicke dem Bot bitte "/start".</small>
@endif

<form method="POST" action="{{ route('settings') }}">
@csrf
<input type="hidden" name="action" value="createTelegramToken"/>
<button type="submit" class="btn btn-primary">Neuen Connect-Code generieren</button>
</form>
</div>
</div>
</div>
Expand All @@ -44,7 +70,8 @@
@endif
<form method="POST" action="/settings" class="form-inline">
@csrf
<input type="email" name="addEmail" placeholder="E-Mail Adresse" class="form-control"/>
<input type="hidden" name="action" value="addEMail"/>
<input type="email" name="email" placeholder="E-Mail Adresse" class="form-control"/>
<button type="submit" class="btn btn-primary">Speichern</button>
</form>
<hr/>
Expand Down
2 changes: 2 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});

Route::post('/telegram/webhook/', 'TelegramController@handleWebhook');

0 comments on commit c85667a

Please sign in to comment.