Skip to content

Commit

Permalink
Merge pull request #16 from ivmelo/dev
Browse files Browse the repository at this point in the history
Inline keyboard, emojis and broadcast system.
  • Loading branch information
ivmelo authored Sep 12, 2016
2 parents fc32a9e + c74d0c9 commit 159d303
Show file tree
Hide file tree
Showing 17 changed files with 190 additions and 47 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,6 @@ MAIL_ENCRYPTION=null
APP_QUEUE_DRIVER=beanstalkd

TELEGRAM_BOT_TOKEN=null

CURRENT_TERM_SUPERIOR=2016.2
CURRENT_TERM_TECNICO=2016.1
40 changes: 40 additions & 0 deletions app/Http/Controllers/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use App\Http\Requests;
use Illuminate\Http\Request;
use App\User;
use Telegram;
use App\Telegram\Tools\Speaker;

class HomeController extends Controller
{
Expand All @@ -28,4 +30,42 @@ public function index()
$users = User::all();
return view('home', compact('users'));
}

/**
* Send a message to all users.
*
* @return \Illuminate\Http\Response
*/
public function sendMessage(Request $request)
{
$users = User::all();

$this->validate($request, [
'message' => 'required'
]);

$sent = [];
$not_sent = [];

foreach ($users as $user) {
if ($user->telegram_id != null) {
try{

Telegram::sendMessage([
'chat_id' => $user->telegram_id,
'text' => $request->message,
'parse_mode' => 'markdown',
'reply_markup' => Speaker::getReplyKeyboardMarkup()
]);

array_push($sent, $user);
} catch (\Exception $e) {
$message = $e->getMessage();
array_push($not_sent, [$user, $message]);
}
}
}

return view('report', ['sent' => $sent, 'not_sent' => $not_sent, 'message' => $request->message]);
}
}
3 changes: 2 additions & 1 deletion app/Http/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@
Route::auth();

Route::get('/home', 'HomeController@index');
Route::post('/home', 'HomeController@sendMessage');

Route::get('/', function(){
return 'suapbot';
return redirect('/home');
});

// Route::get('/', function () {
Expand Down
4 changes: 3 additions & 1 deletion app/Telegram/Commands/AuthorizeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,11 @@ public function handle($arguments)
$situation = $suap_data['situacao'];

// All set, message user.
// And set up keyboard.
$this->replyWithMessage([
'parse_mode' => 'markdown',
'text' => Speaker::authorized($name, $program, $situation)
'text' => Speaker::authorized($name, $program, $situation),
'reply_markup' => Speaker::getReplyKeyboardMarkup()
]);

// Activate notifications.
Expand Down
2 changes: 1 addition & 1 deletion app/Telegram/Commands/CalendarioCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function handle($arguments)

// And send message.
$this->replyWithMessage([
'text' => "Calendário Acadêmico 2016: \n\nhttp://portal.ifrn.edu.br/campus/natalcentral/arquivos/calendario-escolar-2016-aprovado-pelo-conselho-escolar",
'text' => "🗓 Calendário Acadêmico 2016: \n\nhttp://portal.ifrn.edu.br/campus/natalcentral/arquivos/calendario-escolar-2016-aprovado-pelo-conselho-escolar",
'parse_mode' => 'markdown'
]);
}
Expand Down
20 changes: 13 additions & 7 deletions app/Telegram/Commands/ClassesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,19 @@ public function handle($arguments)

// Get schedule for the requested day of the week.
$day = $this->getDayNumber($arguments);
$schedule = $client->getSchedule($day);
$schedule = $client->getSchedule($day, env('CURRENT_TERM_SUPERIOR'));

// Schedule empty, might be a technical student...
if (empty($schedule)) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$schedule = $client->getSchedule($day, env('CURRENT_TERM_TECNICO'));
}

// Choose the appropriate message.
if ($this->isToday($day)) {
$schedule_response = "*Suas aulas de hoje são:*\n\n";
$schedule_response = "*📚 Suas aulas de hoje são:*\n\n";
} else {
$schedule_response = "*Aulas d" . Speaker::getDayOfTheWeek($day, true) . ":*\n\n";
$schedule_response = "*📚 Aulas d" . Speaker::getDayOfTheWeek($day, true) . ":*\n\n";
}

$has_classes = false;
Expand All @@ -61,20 +67,20 @@ public function handle($arguments)
foreach ($hours as $time => $class) {
if ($class) {
$has_classes = true;
$schedule_response .= "*" . $time . ":* \n";
$schedule_response .= $class['disciplina'] . "\n_" . $class['local'] . "_\n\n";
$schedule_response .= "*" . $time . ":* \n";
$schedule_response .= "📓 *" . $class['disciplina'] . "*\n_🏫 " . $class['local'] . "_\n\n";
}
}
}

if (! $has_classes) {
if ($this->isToday($day)) {
// No classes today.
$schedule_response = "Sem aulas hoje. 😃 \nPara ver aulas de outros dias, digite /aulas <dia-da-semana>.";
$schedule_response = "ℹ️ Sem aulas hoje. 😃 \n\nPara ver aulas de outros dias, digite /aulas <dia-da-semana>.";

} else {
// No classes for the requested day.
$schedule_response = "Você não tem aulas no dia socitado. \nPara ver aulas de outros dias, digite /aulas <dia-da-semana>.";
$schedule_response = "ℹ️ Você não tem aulas no dia socitado. \n\nPara ver aulas de outros dias, digite /aulas <dia-da-semana>.";
}
} else {
$schedule_response .= "Para ver aulas de outros dias, digite /aulas <dia-da-semana>.";
Expand Down
6 changes: 4 additions & 2 deletions app/Telegram/Commands/GradesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function handle($arguments)
// No filter results.
if (empty($grades)) {
$this->replyWithMessage([
'text' => 'Não foram encontradas disciplinas contendo o(s) termo(s) "' . $arguments . '" no seu boletim.',
'text' => 'ℹ️ Não foram encontradas disciplinas contendo o(s) termo(s) "' . $arguments . '" no seu boletim.',
'parse_mode' => 'markdown'
]);
}
Expand Down Expand Up @@ -81,7 +81,9 @@ public function handle($arguments)

// If results, parse grades and display them.
if (! empty($grades)) {
$grades_response = Markify::parseBoletim($grades);
$grades_response = "*📚 Suas notas e frequência:*\n\n";

$grades_response .= Markify::parseBoletim($grades);

// Send grades to the user.
$this->replyWithMessage([
Expand Down
4 changes: 2 additions & 2 deletions app/Telegram/Commands/NotifyCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ public function handle($arguments)

$this->replyWithMessage([
'parse_mode' => 'markdown',
'text' => 'As notificações de atualização de boletim foram *ativadas*. Você irá receber notificações quando houver novas faltas, aulas ou notas no seu boletim. Para desativar digite /notificar.'
'text' => "As notificações de atualização de boletim foram *ATIVADAS*. \n\nVocê irá receber notificações quando houver novas faltas, aulas ou notas no seu boletim. \n\nPara desativar digite /notificar."
]);
} else {
$user->notify = false;
$user->save();

$this->replyWithMessage([
'parse_mode' => 'markdown',
'text' => 'As notificações de atualização de boletim foram *desativadas*. Você não receberá mais notificações quando houver novas faltas, aulas ou notas no seu boletim. Para reativar digite /notificar.'
'text' => "🚫 As notificações de atualização de boletim foram *DESATIVADAS*. \n\nVocê não receberá mais notificações quando houver novas faltas, aulas ou notas no seu boletim. \n\nPara reativar digite /notificar."
]);
}
} else {
Expand Down
12 changes: 7 additions & 5 deletions app/Telegram/Commands/StartCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function handle($arguments)
$telegram_id = $updates['message']['from']['id'];
$first_name = $updates['message']['from']['first_name'];

$message = 'Olá, ' . $first_name . '! Eu sou o SUAP Bot, eu posso te mostrar informações sobre suas notas e faltas.'; //Se você quiser, também posso te enviar notificações quando novas notas ou faltas forem lançadas (em breve).
$message = 'Olá ' . $first_name . '. Eu sou o SUAP Bot, eu posso te mostrar informações sobre suas notas, faltas, locais e horários de aula.'; //Se você quiser, também posso te enviar notificações quando novas notas ou faltas forem lançadas (em breve).

$this->replyWithMessage(['text' => $message]);

Expand Down Expand Up @@ -67,14 +67,16 @@ public function handle($arguments)
$response .= sprintf('/%s - %s' . PHP_EOL, $name, $command->getDescription());
}

// Reply with the commands list
$this->replyWithMessage(['text' => $response]);

if (! $user->suap_id) {
$this->replyWithMessage([
'text' => Speaker::tutorial(),
'parse_mode' => 'markdown',
'reply_markup' => ['force_reply']
]);
} else {
// Reply with the commands list
$this->replyWithMessage([
'text' => $response,
'reply_markup' => Speaker::getReplyKeyboardMarkup()
]);
}

Expand Down
2 changes: 1 addition & 1 deletion app/Telegram/Tools/Markify.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static function parseBoletim($grades) {
$response_text = '';

foreach ($grades as $grade) {
$course_info = "*" . $grade['disciplina'] . "*\n";
$course_info = "*📓 " . $grade['disciplina'] . "*\n";

if(isset($grade['aulas']) && $grade['aulas']) {
$course_info .= "Aulas: " . $grade['aulas'] . "\n";
Expand Down
44 changes: 35 additions & 9 deletions app/Telegram/Tools/Speaker.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace App\Telegram\Tools;

use Telegram;

/**
* This class provides strings for the most common messages used through the application.
* It avoids duplicating them, and helps keep the code clean.
Expand All @@ -15,7 +17,7 @@ class Speaker
* @return String The message.
*/
public static function suapError() {
return 'Houve um erro ao conectar-se ao SUAP. Por favor, verifique se o SUAP está online e tente novamente mais tarde.';
return 'Houve um erro ao conectar-se ao SUAP. Por favor, verifique se o SUAP está online e tente novamente mais tarde.';
}

/**
Expand All @@ -24,7 +26,7 @@ public static function suapError() {
* @return String The message.
*/
public static function noCredentials() {
return 'Você ainda não autorizou o acesso ao SUAP. Por favor, digite /autorizar <suap_id> <chave_de_acesso> e tente novamente. Para saber como obter a sua chave de acesso, use o comando /help.';
return '⚠️ Você ainda não autorizou o acesso ao SUAP. Por favor, digite /autorizar <suap_id> <chave_de_acesso> e tente novamente. Para saber como obter a sua chave de acesso, use o comando /help.';
}

/**
Expand All @@ -33,7 +35,7 @@ public static function noCredentials() {
* @return String The message.
*/
public static function userNotFound() {
return 'Houve um erro ao recuperar suas credenciais de acesso. Por favor, digite /start e tente novamente.';
return '⚠️ Houve um erro ao recuperar suas credenciais de acesso. Por favor, digite /start e tente novamente.';
}

/**
Expand All @@ -42,7 +44,7 @@ public static function userNotFound() {
* @return String The message.
*/
public static function about() {
return "O @suapbot foi desenvolvido por: *Ivanilson Melo*\n" .
return "ℹ️ O @suapbot foi desenvolvido por: *Ivanilson Melo*\n" .
"http://github.com/ivmelo\n\n" .
"Aluno do curso de Tecnologia em Análise e Desenvolvimento de Sistemas do IFRN.\n\n" .
"Para ajuda, suporte, sugestões, ou para remover suas informações do bot, contate-me no telegram: @ivanilsonmelo.\n\n" .
Expand All @@ -56,7 +58,7 @@ public static function about() {
* @return String The message.
*/
public static function authorizationError() {
return 'Ocorreu um erro ao autorizar o seu acesso. Por favor, verifique suas credenciais e tente novamente. Caso precise de ajuda, digite /start e siga o tutorial.';
return 'Ocorreu um erro ao autorizar o seu acesso. Por favor, verifique suas credenciais e tente novamente. Caso precise de ajuda, digite /start e siga o tutorial.';
}

/**
Expand All @@ -65,7 +67,7 @@ public static function authorizationError() {
* @return String The message.
*/
public static function authorizationCredentialsMissing() {
return 'Por favor, envie suas credenciais no formato: /autorizar <matricula> <chave-de-acesso>. Caso precise de ajuda, digite /start e siga o tutorial.';
return '⚠️ Por favor, envie suas credenciais no formato: /autorizar <matricula> <chave-de-acesso>. Caso precise de ajuda, digite /start e siga o tutorial.';
}

/**
Expand All @@ -74,11 +76,11 @@ public static function authorizationCredentialsMissing() {
* @return String The message.
*/
public static function authorized($name, $program, $situation) {
return "Pronto, sua conta foi autorizada com sucesso. 🙂\n\n" .
return "Pronto, sua conta foi autorizada com sucesso. 🙂\n\n" .
"*Nome:* $name \n" .
"*Curso:* $program \n" .
"*Situação:* $situation \n\n" .
"Digite /notas para ver suas notas ou /help para ver uma lista de comandos disponíveis.'";
"ℹ️ Digite /notas para ver suas notas, /aulas para ver as aulas de hoje ou /help para ver uma lista de comandos disponíveis.";
}

/**
Expand All @@ -96,7 +98,31 @@ public static function tutorial() {
"4 - Na ultima linha da tabela de “Dados Gerais” procure pela “Chave de Acesso” (Vai ser algo parecido com 5e8h9);\n" .
"5 - Copie ou anote a sua chave de acesso.\n\n" .
"Pronto! Agora basta digitar:\n\n" .
"/autorizar <sua-matricula> <chave-de-acesso>';\n";
"/autorizar <sua-matricula> <chave-de-acesso>\n";
}

/**
* Return a keyboard for the bot.
*
* @return String The message.
*/
public static function getReplyKeyboardMarkup() {
// keyboard system...
$keyboard = [
['/aulas', '/notas'],
['/aulas amanhã', '/calendario'],
// ['/help', '/sobre']
];

$reply_markup = Telegram::replyKeyboardMarkup([
'keyboard' => $keyboard,
'resize_keyboard' => true,
'one_time_keyboard' => false
]);

// $reply_markup = Telegram::replyKeyboardHide();

return $reply_markup;
}

/**
Expand Down
10 changes: 5 additions & 5 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions resources/views/auth/login.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
</div>
</div>

<!--{{--
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
Expand All @@ -48,13 +49,16 @@
</div>
</div>
--}}-->

<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<button type="submit" class="btn btn-primary pull-right">
<i class="fa fa-btn fa-sign-in"></i> Login
</button>

<!--{{--
<a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>
--}}-->
</div>
</div>
</form>
Expand Down
Loading

0 comments on commit 159d303

Please sign in to comment.