Skip to content

Commit

Permalink
Merge pull request #60 from F33RNI/next
Browse files Browse the repository at this point in the history
Next
  • Loading branch information
F33RNI authored Sep 20, 2023
2 parents 118462a + 15805f2 commit 207abe3
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 19 deletions.
41 changes: 33 additions & 8 deletions BotHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ async def send_message_async(config: dict, messages: List[Dict],
index_start = request_response.response_part_positions[-1]
response_part_length = len(request_response.response[index_start:])
if response_part_length > config["telegram"]["one_message_limit"]:
request_response.response_part_positions\
request_response.response_part_positions \
.append(index_start + config["telegram"]["one_message_limit"])
else:
break
Expand Down Expand Up @@ -795,24 +795,43 @@ async def bot_command_broadcast(self, update: Update, context: ContextTypes.DEFA
await _send_safe(user["user_id"], self.messages[lang]["broadcast_no_message"], context)
return

# Send initial message
await _send_safe(user["user_id"], self.messages[lang]["broadcast_initiated"], context)

# Get message
broadcast_message = str(" ".join(context.args)).strip()

# Get list of users
users = self.users_handler.read_users()

# List of successful users
broadcast_ok_users = []

# Broadcast to non-banned users
for broadcast_user in users:
if not broadcast_user["banned"]:
try:
logging.info("broadcasting to: {0} ({1})".format(broadcast_user["user_name"],
broadcast_user["user_id"]))
await telegram.Bot(self.config["telegram"]["api_key"]) \
.sendMessage(chat_id=broadcast_user["user_id"],
text=self.messages[lang]["broadcast"].replace("\\n", "\n").format(
broadcast_message))
# Try to send message and get message ID
message_id = (await telegram.Bot(self.config["telegram"]["api_key"]).sendMessage(
chat_id=broadcast_user["user_id"],
text=self.messages[lang]["broadcast"].replace("\\n", "\n").format(
broadcast_message))).message_id

# Check
if message_id is not None and message_id != 0:
logging.info("Message sent to: {0} ({1})".format(broadcast_user["user_name"],
broadcast_user["user_id"]))
broadcast_ok_users.append(broadcast_user["user_name"])

# Wait some time
time.sleep(self.config["telegram"]["broadcast_delay_per_user_seconds"])
except Exception as e:
logging.error("Error sending message!", exc_info=e)
logging.warning("Error sending message to {}!".format(broadcast_user["user_id"]), exc_info=e)

# Send final message
await _send_safe(user["user_id"],
self.messages[lang]["broadcast_done"].format("\n".join(broadcast_ok_users)),
context)

async def bot_command_ban(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await self.bot_command_ban_unban(True, update, context)
Expand Down Expand Up @@ -933,6 +952,12 @@ async def bot_command_users(self, update: Update, context: ContextTypes.DEFAULT_
else:
message += " "

# Language
message += self.messages[UsersHandler.get_key_or_none(user_info, "lang", 0)]["language_icon"] + " "

# Module
message += self.messages[0]["module_icons"][UsersHandler.get_key_or_none(user_info, "module", 0)] + " "

# User ID, name, total requests
message += "{0} ({1}) - {2}\n".format(user_info["user_id"], user_info["user_name"],
user_info["requests_total"])
Expand Down
7 changes: 5 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@
"one_message_limit": 3000,

"__comment08__": "SET TO true FOR THE BOT TO REPLY TO PLAIN MESSAGES AS WELL AS DIRECT MODULE COMMANDS",
"reply_to_messages": true
"reply_to_messages": true,

"__comment09__": "HOW MANY SECONDS TO WAIT BETWEEN EACH MESSAGE WHEN BROADCASTING",
"broadcast_delay_per_user_seconds": 0.5
},

"__comment08__": "FILES AND DIRECTORIES SETTINGS",
Expand Down Expand Up @@ -213,4 +216,4 @@
"__comment06__": "HOW LONG (SECONDS) TO WAIT A REPLY",
"check_timeout_seconds": 30
}
}
}
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from JSONReaderWriter import load_json

# GPT-Telegramus version
__version__ = "3.4.4"
__version__ = "3.5.0"

# Logging level
LOGGING_LEVEL = logging.INFO
Expand Down
35 changes: 27 additions & 8 deletions messages.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[
{
"language_name": "🇺🇸 English",
"language_icon": "🇺🇸",
"language_select_error": "❌ Error selecting language!\\n\\n{0}",
"language_select": "Please select an interface language",
"language_changed": "🇺🇸 You've selected English\\n\\nYou can change the language at any time by typing the /lang command",
Expand All @@ -21,7 +22,7 @@
"stop_error_not_last": "❌ Error! Can only abort the last request!",
"stop_error": "❌ Error! Can not stop generating!",
"edgegpt_sources": "\\n📄 {0}: {1}",
"users_admin": "Banned? Admin? UserID (Name) - Requests\\n\\n{0}",
"users_admin": "Banned? Admin? Language Module UserID (Name) - Requests\\n\\n{0}",
"restarting": "🙏 Restarting in progress...\\nPlease wait",
"restarting_done": "✅ The restart is completed",
"chat_cleared": "✅ Chat history cleared for {0}",
Expand All @@ -39,6 +40,8 @@
"unban_message_admin": "✅ Unbanned user: {0}",
"broadcast_no_message": "❌ No message to broadcast!",
"broadcast": "📢 {0}",
"broadcast_initiated": "⏳ Broadcasting in progress... Please wait and don't send new messages!",
"broadcast_done": "✅ Broadcast completed! Messages sent to users:\\n{0}",
"style_changed": "✅ Conversation style changed to {0}",
"style_change_error": "❌ Error changing conversation style!\\n\\n{0}",
"style_select": "Your conversation style: {}\\nSelect new conversation style of EdgeGPT,\\nor ignore this message",
Expand All @@ -56,11 +59,19 @@
"🖼 DALL-E",
"🔵 EdgeGPT",
"🖥 Bard",
"🖼 Bing ImageGen"
"🎨 Bing ImageGen"
],
"module_icons": [
"💬",
"🖼",
"🔵",
"🖥",
"🎨"
]
},
{
"language_name": "🇷🇺 Русский",
"language_icon": "🇷🇺",
"language_select": "Пожалуйста, выберите язык интерфейса",
"language_changed": "🇷🇺 Вы выбрали русский язык\\n\\nВы можете изменить язык в любое время прописав команду /lang",
"start_message": "Привет, 👋 чумба! 👋\\n\\n📄 GPT-Telegramus version {0}\\n\\n💜 Разработка: Ферн (F3RNI)\\n💻 Соавторы:\\n1️⃣ Keepalove (Azarell) (Sprav04ka)\\n2️⃣ Sergey Krashevich\\n3️⃣ Wahit Fitriyanto\\n\\n😺 Страница GitHub: https://github.com/F33RNI/GPT-Telegramus\\n\\n🎵 Поддержите проект, купив мою музыку: https://f3rni.bandcamp.com",
Expand All @@ -80,7 +91,7 @@
"stop_error_not_last": "❌ Ошибка! Можно прервать только последний запрос!",
"stop_error": "❌ Ошибка! Невозможно прекратить дегенерацию!",
"edgegpt_sources": "\\n📄 {0}: {1}",
"users_admin": "Забанен? Админ? UserID (Name) - Запросов\\n\\n{0}",
"users_admin": "Забанен? Админ? Язык Модуль UserID (Имя) - Запросов\\n\\n{0}",
"restarting": "🙏 Выполняется перезапуск...\\nПожалуйста, подождите",
"restarting_done": "✅ Перезапуск завершен",
"chat_cleared": "✅ История чата была очищена для {0}",
Expand All @@ -98,6 +109,8 @@
"unban_message_admin": "✅ Разблокирован пользователь: {0}",
"broadcast_no_message": "❌ Нет сообщения для вещания!",
"broadcast": "📢 {0}",
"broadcast_initiated": "⏳ Bещание в процессе... Пожалуйста ожидайте и не отправляйте новых сообщений!",
"broadcast_done": "✅ Вещание завершено! Сообщения отправлены пользователям:\\n{0}",
"style_changed": "✅ Стиль общения изменен на {0}",
"style_change_error": "❌ Ошибка смены стиля общения!\\n\\n{0}",
"style_select": "Текущий стиль общения: {}\\nВыберите новый стиль общения EdgeGPT,\\nИли проигнорируйте это сообщение",
Expand All @@ -115,11 +128,12 @@
"🖼 DALL-E",
"🔵 EdgeGPT",
"🖥 Bard",
"🖼 Bing ImageGen"
"🎨 Bing ImageGen"
]
},
{
"language_name": "🏴‍☠️ Тофийсковый",
"language_icon": "🏴‍☠",
"language_select": "Пожамлуста, выберитеб языкб интерфейсба",
"language_changed": "🏴‍☠️ Вы вымбрали тофийский язык\\n\\nВы можитеб изменитьб язык в любои время прописаф командуб /lang",
"start_message": "Преветб, 👋 тчумба! 👋\\n\\n📄 GPT-Telegramus version {0}\\n\\n💜 Разработбка: Ферн (F3RNI)\\n💻 Соавторы:\\n1️⃣ Keepalove (Azarell) (Sprav04ka)\\n2️⃣ Sergey Krashevich\\n3️⃣ Wahit Fitriyanto\\n\\n😺 Странитса GitHub: https://github.com/F33RNI/GPT-Telegramus\\n\\n🎵 Подержите проектб, купив моюб музыкбу: https://f3rni.bandcamp.com",
Expand All @@ -139,7 +153,7 @@
"stop_error_not_last": "❌ Ошибка! Можноб прерватб толбко последневый запрос!",
"stop_error": "❌ Ошибка! Невозможноб прекратитб дегенерацию!",
"edgegpt_sources": "\\n📄 {0}: {1}",
"users_admin": "Забананенб? Админ? UserID (Name) - Запрософ\\n\\n{0}",
"users_admin": "Забананенб? Админ? Языкб Мобдулб UserID (Name) - Запрософ\\n\\n{0}",
"restarting": "🙏 Выполняется перезампуск...\\nПожамлеста, подождите чучутб",
"restarting_done": "✅ Перезампуск завершен",
"chat_cleared": "✅ История чатба была очищена для {0}",
Expand All @@ -157,6 +171,8 @@
"unban_message_admin": "✅ Разблокирован пользователь: {0}",
"broadcast_no_message": "❌ Нет сообщення для вещання!",
"broadcast": "📢 {0}",
"broadcast_initiated": "⏳ Bесчание в процесбе... Пожамлусто пождите и не черыкайти нововых собщениев!",
"broadcast_done": "✅ Весчание покончено! Собщчення начерыканы юзверям:\\n{0}",
"style_changed": "✅ Стилб общення изменен на {0}",
"style_change_error": "❌ Ошибка смены стиля общення!\\n\\n{0}",
"style_select": "Текущий стиль общення: {}\\nВымберитеб новый стилб общення EdgeGPT,\\nИли проигнорируйте это сообщенне",
Expand All @@ -174,11 +190,12 @@
"🖼 Каляка малака",
"🔵 Девиантнутый",
"🖥 Лютик, мать твою",
"🖼 Маляка каляка"
"🎨 Маляка каляка"
]
},
{
"language_name": "🇮🇩 Bahasa Indonesia",
"language_icon": "🇮🇩",
"language_select_error": "❌ Kesalahan dalam memilih bahasa!\\n\\n{0}",
"language_select": "Silakan pilih bahasa antarmuka",
"language_changed": "🇮🇩 Anda telah memilih Bahasa Indonesia\\n\\nAnda dapat mengganti bahasa kapan saja dengan mengetik perintah /lang",
Expand All @@ -199,7 +216,7 @@
"stop_error_not_last": "❌ Kesalahan! Hanya bisa menghentikan permintaan terakhir!",
"stop_error": "❌ Kesalahan! Tidak dapat menghentikan penghasilan!",
"edgegpt_sources": "\\n📄 {0}: {1}",
"users_admin": "Dilarang? Admin? UserID (Nama) - Permintaan\\n\\n{0}",
"users_admin": "Dilarang? Admin? Bahasa Modul UserID (Nama) - Permintaan\\n\\n{0}",
"restarting": "🙏 Sedang dilakukan proses restart...\\nTunggu sebentar",
"restarting_done": "✅ Restart selesai",
"chat_cleared": "✅ Riwayat obrolan dibersihkan untuk {0}",
Expand All @@ -217,6 +234,8 @@
"unban_message_admin": "✅ Pengguna dibuka blokir: {0}",
"broadcast_no_message": "❌ Tidak ada pesan untuk disiarkan!",
"broadcast": "📢 {0}",
"broadcast_initiated": "⏳ Proses siaran sedang berlangsung... Harap tunggu dan jangan kirim pesan baru!",
"broadcast_done": "✅ Siaran selesai! Pesan telah dikirim ke pengguna:\\n{0}",
"style_changed": "✅ Gaya percakapan diubah menjadi {0}",
"style_change_error": "❌ Kesalahan mengubah gaya percakapan!\\n\\n{0}",
"style_select": "Gaya percakapan Anda: {}\\nPilih gaya percakapan baru EdgeGPT,\\natau abaikan pesan ini",
Expand All @@ -234,7 +253,7 @@
"🖼 DALL-E",
"🔵 EdgeGPT",
"🖥 Bard",
"🖼 Bing ImageGen"
"🎨 Bing ImageGen"
]
}
]

0 comments on commit 207abe3

Please sign in to comment.