chatgpt_assistant 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,38 +26,45 @@ module ChatgptAssistant
26
26
 
27
27
  private
28
28
 
29
- attr_reader :openai_api_key, :response, :message
30
- attr_accessor :chat_id, :json
29
+ attr_reader :openai_api_key, :response, :message
30
+ attr_accessor :chat_id, :json
31
31
 
32
- def error_log
33
- "Algo deu errado, tente novamente mais tarde."
34
- end
32
+ def error_log
33
+ "Algo deu errado, tente novamente mais tarde." # TODO: use a DefaultMessage object
34
+ end
35
35
 
36
- def header
37
- {
38
- "Content-Type": "application/json",
39
- Authorization: "Bearer #{openai_api_key}"
40
- }
41
- end
36
+ def header
37
+ {
38
+ "Content-Type": "application/json",
39
+ Authorization: "Bearer #{openai_api_key}"
40
+ }
41
+ end
42
42
 
43
- def connection
44
- Faraday.new(url: "https://api.openai.com/") do |faraday|
45
- faraday.request :url_encoded
46
- faraday.adapter Faraday.default_adapter
43
+ def connection
44
+ Faraday.new(url: "https://api.openai.com/") do |faraday|
45
+ faraday.request :url_encoded
46
+ faraday.adapter Faraday.default_adapter
47
+ end
47
48
  end
48
- end
49
49
 
50
- def request_params(message)
51
- messages = Message.where(chat_id: chat_id).order(id: :asc).last(10)
52
- messages = messages.empty? ? [{ role: "user", content: message }] : messages.map { |mess| { role: mess.role, content: mess.content } }
53
- {
54
- model: "gpt-3.5-turbo",
55
- messages: messages
56
- }.to_json
57
- end
50
+ def request_params(message)
51
+ messages = Message.where(chat_id: chat_id).order(id: :asc).last(10)
52
+ messages = if messages.empty?
53
+ [{ role: "user", content: message }]
54
+ else
55
+ messages.map do |mess|
56
+ { role: mess.role,
57
+ content: mess.content }
58
+ end
59
+ end
60
+ {
61
+ model: "gpt-3.5-turbo",
62
+ messages: messages
63
+ }.to_json
64
+ end
58
65
 
59
- def request(message)
60
- connection.post("v1/chat/completions", request_params(message), header)
61
- end
66
+ def request(message)
67
+ connection.post("v1/chat/completions", request_params(message), header)
68
+ end
62
69
  end
63
70
  end
@@ -9,23 +9,23 @@ module ChatgptAssistant
9
9
  # This class is responsible for the configuration of the Chatgpt Assistant
10
10
  class Config
11
11
  def initialize
12
- @env_type = ENV["ENV_TYPE"]
13
- @language = ENV["LANGUAGE"]
14
- @mode = ENV["MODE"]
15
- @database_host = ENV["POSTGRES_HOST"]
16
- @database_name = ENV["POSTGRES_DB"]
17
- @database_username = ENV["POSTGRES_USER"]
18
- @database_password = ENV["POSTGRES_PASSWORD"]
19
- @openai_api_key = ENV["OPENAI_API_KEY"]
20
- @telegram_token = ENV["TELEGRAM_TOKEN"]
21
- @discord_token = ENV["DISCORD_TOKEN"]
22
- @discord_client_id = ENV["DISCORD_CLIENT_ID"]
23
- @ibm_api_key = ENV["IBM_API_KEY"]
24
- @ibm_url = ENV["IBM_URL"]
25
- @aws_access_key_id = ENV["AWS_ACCESS_KEY_ID"]
26
- @aws_secret_access_key = ENV["AWS_SECRET_ACCESS_KEY"]
27
- @aws_region = ENV["AWS_REGION"]
28
- @discord_prefix = ENV["DISCORD_PREFIX"]
12
+ @env_type = ENV.fetch("ENV_TYPE", nil)
13
+ @language = ENV.fetch("LANGUAGE", nil)
14
+ @mode = ENV.fetch("MODE", nil)
15
+ @database_host = ENV.fetch("POSTGRES_HOST", nil)
16
+ @database_name = ENV.fetch("POSTGRES_DB", nil)
17
+ @database_username = ENV.fetch("POSTGRES_USER", nil)
18
+ @database_password = ENV.fetch("POSTGRES_PASSWORD", nil)
19
+ @openai_api_key = ENV.fetch("OPENAI_API_KEY", nil)
20
+ @telegram_token = ENV.fetch("TELEGRAM_TOKEN", nil)
21
+ @discord_token = ENV.fetch("DISCORD_TOKEN", nil)
22
+ @discord_client_id = ENV.fetch("DISCORD_CLIENT_ID", nil)
23
+ @ibm_api_key = ENV.fetch("IBM_API_KEY", nil)
24
+ @ibm_url = ENV.fetch("IBM_URL", nil)
25
+ @aws_access_key_id = ENV.fetch("AWS_ACCESS_KEY_ID", nil)
26
+ @aws_secret_access_key = ENV.fetch("AWS_SECRET_ACCESS_KEY", nil)
27
+ @aws_region = ENV.fetch("AWS_REGION", nil)
28
+ @discord_prefix = ENV.fetch("DISCORD_PREFIX", nil)
29
29
  end
30
30
 
31
31
  attr_reader :openai_api_key, :telegram_token, :discord_token, :ibm_api_key, :ibm_url,
@@ -47,13 +47,17 @@ module ChatgptAssistant
47
47
  def migrate
48
48
  db_connection
49
49
  ActiveRecord::Base.logger = Logger.new($stdout)
50
+ VisitorMigration.new.migrate(:up)
51
+ VisitorActionsMigration.new.migrate(:up)
50
52
  UserMigration.new.migrate(:up)
53
+ UserActionsMigration.new.migrate(:up)
51
54
  ChatMigration.new.migrate(:up)
52
55
  MessageMigration.new.migrate(:up)
56
+ ErrorMigration.new.migrate(:up)
53
57
  end
54
58
 
55
59
  private
56
60
 
57
- attr_reader :database_host, :database_name, :database_username, :database_password
61
+ attr_reader :database_host, :database_name, :database_username, :database_password
58
62
  end
59
63
  end
@@ -19,130 +19,130 @@ module ChatgptAssistant
19
19
 
20
20
  private
21
21
 
22
- def commom_messages_pt
23
- {
24
- start: "Olá, eu sou o Chatgpt Assistant, um chatbot que usa a API da OpenAI para responder suas perguntas no Telegram e Discord.",
25
- stop: "Até mais!",
26
- start_helper: "Primeiro, é necessário cadastrar seu usuário no banco de dados.
22
+ def commom_messages_pt
23
+ {
24
+ start: "Olá, eu sou o Chatgpt Assistant, um chatbot que usa a API da OpenAI para responder suas perguntas no Telegram e Discord.",
25
+ stop: "Até mais!",
26
+ start_helper: "Primeiro, é necessário cadastrar seu usuário no banco de dados.
27
27
  \nPara isso, mande ume mensagem com seu email e senha de acesso de 4 digitos.
28
28
  \nExemplo: register/user@email.com:1234",
29
- start_sec_helper: "Caso você já tenha um usuário cadastrado, basta fazer login.
29
+ start_sec_helper: "Caso você já tenha um usuário cadastrado, basta fazer login.
30
30
  \nExemplo: login/user@email.com:3214",
31
- register: "Para se registrar no sistema, digite register/email:senha (a senha deve ser um numero de 4 digitos ex: 1234).
31
+ register: "Para se registrar no sistema, digite register/email:senha (a senha deve ser um numero de 4 digitos ex: 1234).
32
32
  \nExemplo de Registro: register/user@email.com:3214",
33
- login: "Para fazer login no sistema, digite login/email:senha (a senha deve ser um numero de 4 digitos ex: 1234).
33
+ login: "Para fazer login no sistema, digite login/email:senha (a senha deve ser um numero de 4 digitos ex: 1234).
34
34
  \nExemplo de Login: login/user@mail.com:2134",
35
- chat_list: "Aqui estão os chats que você criou:"
36
- }
37
- end
35
+ chat_list: "Aqui estão os chats que você criou:"
36
+ }
37
+ end
38
38
 
39
- def success_messages_pt
40
- {
41
- user_created: "Usuário criado com sucesso!",
42
- chat_created: "Chat criado com sucesso!",
43
- chat_selected: "Chat selecionado com sucesso!",
44
- user_logged_in: "Login realizado com sucesso!",
45
- voice_channel_connected: "O bot entrou no canal de voz com sucesso!"
46
- }
47
- end
39
+ def success_messages_pt
40
+ {
41
+ user_created: "Usuário criado com sucesso!",
42
+ chat_created: "Chat criado com sucesso!",
43
+ chat_selected: "Chat selecionado com sucesso!",
44
+ user_logged_in: "Login realizado com sucesso!",
45
+ voice_channel_connected: "O bot entrou no canal de voz com sucesso!"
46
+ }
47
+ end
48
48
 
49
- def error_messages_pt
50
- {
51
- nil: "Não entendi o que você disse. Tente novamente",
52
- email: "O email que você digitou não é válido. Tente novamente",
53
- password: "A senha que você digitou não é válida. Tente novamente",
54
- wrong_password: "A senha que você digitou não é válida. Tente novamente",
55
- user: "O usuário que você digitou não existe. Tente novamente",
56
- user_creation: "Erro ao criar usuário. Tente novamente",
57
- user_already_exists: "O usuário que você digitou já existe. Tente novamente",
58
- chat_creation: "Erro ao criar chat. Tente novamente",
59
- no_messages_founded: "Nenhuma mensagem encontrada",
60
- no_chat_selected: "Nenhum chat selecionado",
61
- chat_not_found: "Chat não encontrado",
62
- no_chats_founded: "Nenhum chat encontrado",
63
- user_not_logged_in: "Usuário não logado",
64
- user_not_found: "Usuário não encontrado",
65
- something_went_wrong: "Algo deu errado. Tente novamente mais tarde.",
66
- message_history_too_long: "O histórico mensagem é muito longo.",
67
- text_length: "O texto de resposta é muito longo. Tente diminuir a quantidade de respostas na mesma mensagem.",
68
- user_not_in_voice_channel: "Você não está em um canal de voz.",
69
- bot_not_in_voice_channel: "O bot não está em um canal de voz.",
70
- invalid_command: "Comando inválido. Tente novamente.",
71
- message_creation_error: "Erro ao criar mensagem. Tente novamente."
72
- }
73
- end
49
+ def error_messages_pt
50
+ {
51
+ nil: "Não entendi o que você disse. Tente novamente",
52
+ email: "O email que você digitou não é válido. Tente novamente",
53
+ password: "A senha que você digitou não é válida. Tente novamente",
54
+ wrong_password: "A senha que você digitou não é válida. Tente novamente",
55
+ user: "O usuário que você digitou não existe. Tente novamente",
56
+ user_creation: "Erro ao criar usuário. Tente novamente",
57
+ user_already_exists: "O usuário que você digitou já existe. Tente novamente",
58
+ chat_creation: "Erro ao criar chat. Tente novamente",
59
+ no_messages_founded: "Nenhuma mensagem encontrada",
60
+ no_chat_selected: "Nenhum chat selecionado",
61
+ chat_not_found: "Chat não encontrado",
62
+ no_chats_founded: "Nenhum chat encontrado",
63
+ user_not_logged_in: "Usuário não logado",
64
+ user_not_found: "Usuário não encontrado",
65
+ something_went_wrong: "Algo deu errado. Tente novamente mais tarde.",
66
+ message_history_too_long: "O histórico mensagem é muito longo.",
67
+ text_length: "O texto de resposta é muito longo. Tente diminuir a quantidade de respostas na mesma mensagem.",
68
+ user_not_in_voice_channel: "Você não está em um canal de voz.",
69
+ bot_not_in_voice_channel: "O bot não está em um canal de voz.",
70
+ invalid_command: "Comando inválido. Tente novamente.",
71
+ message_creation_error: "Erro ao criar mensagem. Tente novamente."
72
+ }
73
+ end
74
74
 
75
- def help_messages_pt
76
- ["Para começar a conversar comigo, digite /start",
77
- "Para parar de conversar comigo, digite /stop",
78
- "Para se registrar no sistema, digite register/email:senha (a senha deve ser um numero de 4 digitos ex: 1234)",
79
- "Para fazer login no sistema, digite login/email:senha (a senha deve ser um numero de 4 digitos ex: 1234)",
80
- "Para criar um novo chat, digite new_chat/nome do chat",
81
- "Para selecionar um chat, digite sl_chat/nome do chat",
82
- "Para listar os chats que você criou, digite /list",
83
- "Para ver esta mensagem novamente, digite /help"]
84
- end
75
+ def help_messages_pt
76
+ ["Para começar a conversar comigo, digite /start",
77
+ "Para parar de conversar comigo, digite /stop",
78
+ "Para se registrar no sistema, digite register/email:senha (a senha deve ser um numero de 4 digitos ex: 1234)",
79
+ "Para fazer login no sistema, digite login/email:senha (a senha deve ser um numero de 4 digitos ex: 1234)",
80
+ "Para criar um novo chat, digite new_chat/nome do chat",
81
+ "Para selecionar um chat, digite sl_chat/nome do chat",
82
+ "Para listar os chats que você criou, digite /list",
83
+ "Para ver esta mensagem novamente, digite /help"]
84
+ end
85
85
 
86
- def commom_messages_en
87
- {
88
- start: "Hello, I'm the Chatgpt Assistant, a chatbot that uses the OpenAI API to answer your questions on Telegram and Discord.",
89
- stop: "See you later!",
90
- start_helper: "First, you need to register your user in the database.
86
+ def commom_messages_en
87
+ {
88
+ start: "Hello, I'm the Chatgpt Assistant, a chatbot that uses the OpenAI API to answer your questions on Telegram and Discord.",
89
+ stop: "See you later!",
90
+ start_helper: "First, you need to register your user in the database.
91
91
  \nTo do this, send a message with your email and password of 4 digits access.
92
92
  \nExample: register/user@mail.com:3421",
93
- start_sec_helper: "If you already have a registered user, just log in.
93
+ start_sec_helper: "If you already have a registered user, just log in.
94
94
  \nExample: login/user@mail.com:5423",
95
- register: "To register in the system, type register/email:password (the password must be a 4 digit number ex: 1234).
95
+ register: "To register in the system, type register/email:password (the password must be a 4 digit number ex: 1234).
96
96
  \nExample of Registration: register/user@mail.com:3241",
97
- login: "To log in to the system, type login/email:password (the password must be a 4 digit number ex: 1234).
97
+ login: "To log in to the system, type login/email:password (the password must be a 4 digit number ex: 1234).
98
98
  \nExample of Login: login/user@mail.com:2134",
99
- chat_list: "Here are the chats you created:"
100
- }
101
- end
99
+ chat_list: "Here are the chats you created:"
100
+ }
101
+ end
102
102
 
103
- def success_messages_en
104
- {
105
- user_created: "User created successfully!",
106
- chat_created: "Chat created successfully!",
107
- chat_selected: "Chat selected successfully!",
108
- user_logged_in: "Login successfully!"
109
- }
110
- end
103
+ def success_messages_en
104
+ {
105
+ user_created: "User created successfully!",
106
+ chat_created: "Chat created successfully!",
107
+ chat_selected: "Chat selected successfully!",
108
+ user_logged_in: "Login successfully!"
109
+ }
110
+ end
111
111
 
112
- def error_messages_en
113
- {
114
- nil: "I didn't understand what you said. Try again",
115
- email: "The email you typed is not valid. Try again",
116
- password: "The password you typed is not valid. Try again",
117
- wrong_password: "The password you typed is not valid. Try again",
118
- user: "The user you typed does not exist. Try again",
119
- user_creation: "Error creating user. Try again",
120
- chat_creation: "Error creating chat. Try again",
121
- no_messages_founded: "No messages found",
122
- no_chat_selected: "No chat selected",
123
- no_chats_founded: "No chats found",
124
- chat_not_found: "Chat not found",
125
- user_not_logged_in: "User not logged in",
126
- user_not_found: "User not found",
127
- something_went_wrong: "Something went wrong. Try again later.",
128
- message_history_too_long: "The message history is too long.",
129
- text_length: "The response text is too long. Try to reduce the number of answers in the same message.",
130
- user_not_in_voice_channel: "You are not in a voice channel.",
131
- bot_not_in_voice_channel: "The bot is not in a voice channel.",
132
- invalid_command: "Invalid command. Try again.",
133
- message_creation_error: "Error creating message. Try again."
134
- }
135
- end
112
+ def error_messages_en
113
+ {
114
+ nil: "I didn't understand what you said. Try again",
115
+ email: "The email you typed is not valid. Try again",
116
+ password: "The password you typed is not valid. Try again",
117
+ wrong_password: "The password you typed is not valid. Try again",
118
+ user: "The user you typed does not exist. Try again",
119
+ user_creation: "Error creating user. Try again",
120
+ chat_creation: "Error creating chat. Try again",
121
+ no_messages_founded: "No messages found",
122
+ no_chat_selected: "No chat selected",
123
+ no_chats_founded: "No chats found",
124
+ chat_not_found: "Chat not found",
125
+ user_not_logged_in: "User not logged in",
126
+ user_not_found: "User not found",
127
+ something_went_wrong: "Something went wrong. Try again later.",
128
+ message_history_too_long: "The message history is too long.",
129
+ text_length: "The response text is too long. Try to reduce the number of answers in the same message.",
130
+ user_not_in_voice_channel: "You are not in a voice channel.",
131
+ bot_not_in_voice_channel: "The bot is not in a voice channel.",
132
+ invalid_command: "Invalid command. Try again.",
133
+ message_creation_error: "Error creating message. Try again."
134
+ }
135
+ end
136
136
 
137
- def help_messages_en
138
- ["To start talking to me, type /start",
139
- "To stop talking to me, type /stop",
140
- "To register in the system, type register/email:password (the password must be a 4 digit number ex: 1234)",
141
- "To log in to the system, type login/email:password (the password must be a 4 digit number ex: 1234)",
142
- "To create a new chat, type new_chat/chat name",
143
- "To select a chat, type sl_chat/chat name",
144
- "To list the chats you created, type /list",
145
- "To see this message again, type /help"]
146
- end
137
+ def help_messages_en
138
+ ["To start talking to me, type /start",
139
+ "To stop talking to me, type /stop",
140
+ "To register in the system, type register/email:password (the password must be a 4 digit number ex: 1234)",
141
+ "To log in to the system, type login/email:password (the password must be a 4 digit number ex: 1234)",
142
+ "To create a new chat, type new_chat/chat name",
143
+ "To select a chat, type sl_chat/chat name",
144
+ "To list the chats you created, type /list",
145
+ "To see this message again, type /help"]
146
+ end
147
147
  end
148
148
  end
@@ -3,7 +3,36 @@
3
3
  require "active_record"
4
4
  require "active_model"
5
5
 
6
- # This file contains the migrations for the database tables
6
+ # Visitor model
7
+ class VisitorMigration < ActiveRecord::Migration[5.2]
8
+ def change
9
+ return if ActiveRecord::Base.connection.table_exists? :visitors
10
+
11
+ create_table :visitors do |t|
12
+ t.string :telegram_id, limit: 100
13
+ t.string :discord_id, limit: 100
14
+ t.integer :platform, null: false, default: 0
15
+ t.string :name, null: false
16
+ t.integer :current_user_id, default: 0
17
+ t.timestamps
18
+ end
19
+ end
20
+ end
21
+
22
+ # VisitorActions model
23
+ class VisitorActionsMigration < ActiveRecord::Migration[5.2]
24
+ def change
25
+ return if ActiveRecord::Base.connection.table_exists? :visitor_actions
26
+
27
+ create_table :visitor_actions do |t|
28
+ t.references :visitor, null: false, foreign_key: true
29
+ t.text :action, null: false
30
+ t.text :description, null: false
31
+ t.integer :role, null: false, default: 0
32
+ t.timestamps
33
+ end
34
+ end
35
+ end
7
36
 
8
37
  # User model
9
38
  class UserMigration < ActiveRecord::Migration[5.2]
@@ -11,12 +40,11 @@ class UserMigration < ActiveRecord::Migration[5.2]
11
40
  return if ActiveRecord::Base.connection.table_exists? :users
12
41
 
13
42
  create_table :users do |t|
43
+ t.string :telegram_id, foreign_key: true, class_name: "Visitor"
44
+ t.string :discord_id, foreign_key: true, class_name: "Visitor"
14
45
  t.string :email, null: false, limit: 100
15
46
  t.string :password_hash, null: false, limit: 100
16
47
  t.string :password_salt, null: false, limit: 100
17
- t.string :name, null: false, limit: 100
18
- t.string :telegram_id, limit: 100
19
- t.string :discord_id, limit: 100
20
48
  t.integer :current_chat_id, null: false, default: 0
21
49
  t.integer :role, null: false, default: 0
22
50
  t.integer :open_chats, null: false, default: 0
@@ -28,6 +56,21 @@ class UserMigration < ActiveRecord::Migration[5.2]
28
56
  end
29
57
  end
30
58
 
59
+ # UserActions model
60
+ class UserActionsMigration < ActiveRecord::Migration[5.2]
61
+ def change
62
+ return if ActiveRecord::Base.connection.table_exists? :user_actions
63
+
64
+ create_table :user_actions do |t|
65
+ t.references :user, null: false, foreign_key: true
66
+ t.text :action, null: false, default: ""
67
+ t.text :description, null: false, default: ""
68
+ t.integer :role, null: false, default: 0
69
+ t.timestamps
70
+ end
71
+ end
72
+ end
73
+
31
74
  # Chat model
32
75
  class ChatMigration < ActiveRecord::Migration[5.2]
33
76
  def change
@@ -55,3 +98,18 @@ class MessageMigration < ActiveRecord::Migration[5.2]
55
98
  end
56
99
  end
57
100
  end
101
+
102
+ # Error model
103
+ class ErrorMigration < ActiveRecord::Migration[5.2]
104
+ def change
105
+ return if ActiveRecord::Base.connection.table_exists? :errors
106
+
107
+ create_table :errors do |t|
108
+ t.integer :chat_id
109
+ t.integer :user_id
110
+ t.text :message, null: false, default: ""
111
+ t.text :backtrace, null: false, array: true, default: []
112
+ t.timestamps
113
+ end
114
+ end
115
+ end
@@ -2,23 +2,53 @@
2
2
 
3
3
  require "active_record"
4
4
 
5
+ # Visitor model
6
+ class Visitor < ActiveRecord::Base
7
+ has_many :visitor_actions
8
+ # has_one :tel_user, foreign_key: "telegram_id", class_name: "User"
9
+ # has_one :dis_user, foreign_key: "discord_id", class_name: "User"
10
+ validates :name, presence: true
11
+ validates :platform, presence: true
12
+ enum platform: { telegram: 0, discord: 1 }
13
+
14
+ def tel_user
15
+ User.find_by(telegram_id: telegram_id)
16
+ end
17
+
18
+ def dis_user
19
+ User.find_by(discord_id: discord_id)
20
+ end
21
+ end
22
+
23
+ # VisitorActions model
24
+ class VisitorAction < ActiveRecord::Base
25
+ belongs_to :visitor
26
+ validates :action, presence: true
27
+ validates :description, presence: true
28
+ validates :role, presence: true
29
+ enum role: { user: 0, assistant: 1, warning: 2 }
30
+ end
31
+
5
32
  # User model
6
33
  class User < ActiveRecord::Base
7
- before_save :generate_password_salt
34
+ attr_accessor :password
35
+
36
+ belongs_to :tel_visitor, optional: true, foreign_key: "telegram_id", class_name: "Visitor"
37
+ belongs_to :dis_visitor, optional: true, foreign_key: "discord_id", class_name: "Visitor"
38
+ before_save :encrypt_password
8
39
  validates :email, presence: true, uniqueness: true
9
- validates :password_hash, presence: true
10
- validates :name, presence: true
11
40
  validates :role, presence: true
12
41
  validates :open_chats, presence: true
13
42
  validates :closed_chats, presence: true
14
43
  validates :total_chats, presence: true
15
44
  validates :total_messages, presence: true
16
-
17
45
  has_many :chats
18
46
 
19
- def generate_password_salt
20
- self.password_salt = BCrypt::Engine.generate_salt
21
- self.password_hash = BCrypt::Engine.hash_secret(password_hash, password_salt)
47
+ def encrypt_password
48
+ return if password.nil?
49
+
50
+ self.password_salt = BCrypt::Engine.generate_salt.to_s
51
+ self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
22
52
  end
23
53
 
24
54
  def current_chat
@@ -34,6 +64,16 @@ class User < ActiveRecord::Base
34
64
  end
35
65
  end
36
66
 
67
+ # UserActions model
68
+ class UserAction < ActiveRecord::Base
69
+ belongs_to :user
70
+ validates :user_id, presence: true
71
+ validates :action, presence: true
72
+ validates :description, presence: true
73
+ validates :role, presence: true
74
+ enum role: { user: 0, assistant: 1, warning: 2 }
75
+ end
76
+
37
77
  # Chat model
38
78
  class Chat < ActiveRecord::Base
39
79
  validates :user_id, presence: true
@@ -51,3 +91,9 @@ class Message < ActiveRecord::Base
51
91
 
52
92
  belongs_to :chat
53
93
  end
94
+
95
+ # Error model
96
+ class Error < ActiveRecord::Base
97
+ validates :message, presence: true
98
+ validates :backtrace, presence: true
99
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ChatgptAssistant
4
- VERSION = "0.1.2"
4
+ VERSION = "0.1.4"
5
5
  end
@@ -31,26 +31,38 @@ module ChatgptAssistant
31
31
  return discord_bot if discord_mode?
32
32
 
33
33
  raise "Invalid mode"
34
+ rescue StandardError => e
35
+ save_error(e)
36
+ retry
34
37
  end
35
38
 
36
39
  private
37
40
 
38
- attr_reader :mode, :config
41
+ attr_reader :mode, :config
39
42
 
40
- def telegram_mode?
41
- mode == "telegram"
42
- end
43
+ def save_error(err)
44
+ puts "Error: #{err.message}"
45
+ err.backtrace.each { |line| puts line }
46
+ Error.create(message: err.message, backtrace: err.backtrace) unless err.message == Error.last&.message
47
+ rescue StandardError
48
+ puts "Error: #{err.message}"
49
+ puts "Backtrace: #{err.backtrace}"
50
+ end
43
51
 
44
- def telegram_bot
45
- TelegramBot.new(config).start
46
- end
52
+ def telegram_mode?
53
+ mode == "telegram"
54
+ end
47
55
 
48
- def discord_mode?
49
- mode == "discord"
50
- end
56
+ def telegram_bot
57
+ TelegramBot.new(config).start
58
+ end
51
59
 
52
- def discord_bot
53
- DiscordBot.new(config).start
54
- end
60
+ def discord_mode?
61
+ mode == "discord"
62
+ end
63
+
64
+ def discord_bot
65
+ DiscordBot.new(config).start
66
+ end
55
67
  end
56
68
  end
@@ -0,0 +1,19 @@
1
+ # github actions ubuntu ssh deploy to server
2
+ name: Deploy to server
3
+
4
+ on:
5
+ push:
6
+ branches:
7
+ - master
8
+
9
+ jobs:
10
+ deploy:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v2
14
+ - name: Deploy & Restart server
15
+ run: |
16
+ mkdir -p ~/.ssh |
17
+ echo "${{ secrets.SSH_KEY }}" > ~/.ssh/telegram_server.pem
18
+ chmod 600 ~/.ssh/telegram_server.pem
19
+ ssh -i ~/.ssh/telegram_server.pem -o StrictHostKeyChecking=no ${{ secrets.USERNAME }}@${{ secrets.HOST }} 'bash -s' < ./deploy.sh
@@ -0,0 +1,19 @@
1
+ # github actions ubuntu ssh deploy to server
2
+ name: Deploy and Build Server
3
+
4
+ on:
5
+ push:
6
+ branches:
7
+ - master
8
+
9
+ jobs:
10
+ deploy_and_build:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v2
14
+ - name: Deploy, Build & Restart server
15
+ run: |
16
+ mkdir -p ~/.ssh |
17
+ echo "${{ secrets.SSH_KEY }}" > ~/.ssh/telegram_server.pem
18
+ chmod 600 ~/.ssh/telegram_server.pem
19
+ ssh -i ~/.ssh/telegram_server.pem -o StrictHostKeyChecking=no ${{ secrets.USERNAME }}@${{ secrets.HOST }} 'bash -s' < ./deploy_and_build.sh