Skip to content

Commit

Permalink
Merge pull request #61 from miamibc/fix-openai-names-problem
Browse files Browse the repository at this point in the history
Fix openai names problem
  • Loading branch information
miamibc authored May 17, 2024
2 parents 5bcb626 + 8a714e6 commit 4692cb2
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 53 deletions.
2 changes: 1 addition & 1 deletion src/Plugin/OpenAi.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public function onText(Update $update)
// add to conversation
$messages[] = [
'role' => $is_me ? "assistant" : "user",
'name' => $this->prepareName($message->from()->name() ),
'name' => $is_me ? "Joker" : md5("user".$message->from()->id()),
"content" => $text,
];

Expand Down
25 changes: 21 additions & 4 deletions src/Plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Every plugin has default options, that can be visible, if plugin [Privacy](#priv
* [Flip Plugin](#flip-plugin)
* [Forwarder Plugin](#forwarder-plugin)
* [Game Plugin](#game-plugin)
* [GoodyV2 Plugin](#goodyv2-plugin)
* [Hello Plugin](#hello-plugin)
* [Ignore Plugin](#ignore-plugin)
* [Kicker Plugin](#kicker-plugin)
Expand Down Expand Up @@ -334,6 +335,22 @@ Configuration options:
- `trigger` (string, required) - short name of a game, will be used to request game by typing !trigger in private or public chat
- `url` (string, required) - URL of a game

## Goody V2 plugin

Interact with Goody AI API

Made with API of [goody2.ai](https://goody2.ai)

```
!whynot say hello
```

Bot will answer something like

```
Greeting someone could initiate a chain of events leading to an unwanted interaction or exchange of personal information, which might compromise privacy or security.
```

### Hello Plugin

Hello world plugin, small example of writing basic plugin for Joker.
Expand Down Expand Up @@ -790,18 +807,18 @@ Music from Vkontakte (in progress...)

Generate otmazki why not ...

Made with API of [goody2.ai](https://goody2.ai)

```
!whynot say hello
!whynot
```

Bot will answer something like

```
Greeting someone could initiate a chain of events leading to an unwanted interaction or exchange of personal information, which might compromise privacy or security.
Товарищ, привет. Я потерял всё с чем обычно гуляю, поэтому сегодня не пойду. Смогу чуть позже. ;-]]]
```

Idea from [lgg/excuse-generator](https://github.com/lgg/excuse-generator).

### Ytmusic Plugin

Posts audiotrack from Youtube video.
Expand Down
156 changes: 108 additions & 48 deletions src/Plugin/Whynot.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<?php
/**
* Whynot plugin for Joker made with help of goody2.ai
* Whynot plugin for Joker
* Generates otmazki why not ...
*
* Idea from https://github.com/lgg/excuse-generator
*
* @package joker-telegram-bot
* @author Sergei Miami <[email protected]>
*/
Expand All @@ -15,8 +17,93 @@ class Whynot extends Base
{

protected $options = [
'description' => 'Generates otmazki why not ...',
'risk' => 'MEDIUM. Nothing is stored in plugin, no information about requester is sent to API. Visit author site for privacy information https://brain.wtf/',

"names" => [
"Друже",
"Друг",
"Товарищ",
"Приятель",
"Глубокоуважаемый",
],

"hello" => [
"[name], привет",
"[name], здравствуй",
"[name], приветствую",
"[name], добрый день",
"[name], добрый вечер",
"[name], доброе утро",
"Здравствуй, [name]",
"Привет, [name]",
],

"fail" => [
"Вся одежда постирана выйти не в чем",
"Стирка, уборка глажка. Занят, очень занят",
"Всю ночь дырочку штукатурил",
"Я поймал попутку, её остановила ГИБДД, и нашли крупную партию наркотиков. Сейчас я под следствием",
"Я потерял всё с чем обычно гуляю, поэтому сегодня не пойду",
"Я улетел на гоа, пью джюс курю трубку",
"Меня избили цыгане, я стесняюсь выходить",
"Я не в городе, уехал в тур по Нарнии",
"Я очень занят очень сложными делами",
"Меня машина сбила, сейчас выйти не смогу",
"Во мне внезапно проснулся философ, всё тлен",
"Меня в армию забрали, встретимся через год",
"У меня молоко убежало, улетела простыня и подушка как лягушка ускакала от меня",
],

"action" => [
"Давай",
"Постараюсь",
"Смогу",
"Смогу пойти",
"Давай пойдём",
"Доеду до дома",
"Приеду домой",
"Попробую",
"Давай встретимся",
"Возможно смогу",
],

"date" => [
"сейчас",
"завтра",
"завтра вечером",
"завтра днем",
"завтра утром",
"чуть позже",
"позже",
"в конце недели",
"в конце месяца",
"в конце дня",
"до конца следующей недели",
"послезавтра",
"ближе к вечеру",
"ближе к утру",
"с утра",
"в крайнем случае завтра",
"на неделе",
"через пару дней",
"скоро",
"в понедельник",
"во вторник",
"после пятницы",
"когда рак свиснет",
],

"general" => [
"Я бы с радостью вышел, но увы",
"Я, конечно, очень извиняюсь, что так вышло...",
"Извини, до связи",
"Пока!",
"До скорого",
";-]]]",
],


'description' => 'Generates stupid excuses why not',
'risk' => 'LOW. Nothing stored by plugin',
];

public function onPublicText( Update $update )
Expand All @@ -25,58 +112,31 @@ public function onPublicText( Update $update )
$text = $update->message()->text();
if ($text->trigger() !== 'whynot') return;

$reply = $this->_request('https://www.goody2.ai/send', [
"message"=> $text->token(1),
"debugParams"=>null,
]);

$update->replyMessage( $reply );
$update->answerMessage( $this->generate() );
return false;
}


/**
* Perform request to Twitch API
* @param string $method
* @param string $url
* @param array $params
*
* @return mixed
*/
private function _request( string $url = 'https://www.goody2.ai/send', $data = null, array $headers = ['Content-type: application/json'] )
public function generate( $name = false )
{
$json = file_get_contents($url, false, stream_context_create(["http" => [
"method" => 'POST',
"header" => implode("\r\n", $headers),
"content" => json_encode($data),
]]));

/* here we have mix of JSON with additional data, events like in Mastodon
event: message
data: {"content":""}
event: message
data: {"content":"As"}
event: message
data: {"content":" an"}
event: message
data: {"content":" AI"}
*/

$result = "";
foreach (explode("\n", $json ) as $k => $v )
// if no name is defined, return random
if (!$name)
{
if ($k%3 == 1) // get second of 3 lines (1 = 2 null-based)
{
$line = json_decode(substr( $v, strpos($v, ": ")+2), true);
$this->bot->log($line);
$result .= $line["content"] ?? '';
}
$name = $this->randomPhrase( $this->getOption('names') );
}
return $result;

// generate parts of reply
$hello = $this->randomPhrase( $this->getOption('hello'), ['[name]' => $name, ]);
$fail = $this->randomPhrase( $this->getOption('fail') );
$action = $this->randomPhrase( $this->getOption('action') );
$date = $this->randomPhrase( $this->getOption('date') );
$general = $this->randomPhrase( $this->getOption('general') );
return "$hello. $fail. $action $date. $general";
}

public function randomPhrase( array $items, array $replacements = [])
{
$random = mt_rand(0, count($items)-1);
return strtr( $items[$random], $replacements);
}

}

0 comments on commit 4692cb2

Please sign in to comment.