Compare commits

...

47 Commits

Author SHA1 Message Date
Simple_Not
0278189ded bring it back
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-17 15:21:28 +10:00
Simple_Not
a842b3ae01 bring it back
Some checks failed
continuous-integration/drone/push Build is failing
2023-07-17 15:19:03 +10:00
Simple_Not
d427d189b1 bring it back
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-17 15:18:56 +10:00
Simple_Not
08cc6b40c1 remake many certs
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-17 14:41:29 +10:00
Simple_Not
ba0867f662 remake many certs
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-17 12:36:06 +10:00
Simple_Not
c764b71af0 fixxxxx
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-16 14:45:35 +10:00
Simple_Not
b9cd608d9b fixxxxx
Some checks failed
continuous-integration/drone/push Build is failing
2023-07-16 14:45:12 +10:00
Simple_Not
77b6293ea6 fixxxxx
Some checks failed
continuous-integration/drone/push Build is failing
2023-07-16 14:34:49 +10:00
Simple_Not
8c269fd768 fixxxxx
Some checks failed
continuous-integration/drone/push Build is failing
2023-07-16 14:29:54 +10:00
Simple_Not
256bdfb89b fixxxxx
Some checks failed
continuous-integration/drone/push Build is failing
2023-07-16 14:24:23 +10:00
Simple_Not
b5903bf79f ZERO worked
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-16 02:00:21 +10:00
Simple_Not
11ddb1536c unittest pipisa
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-16 01:53:33 +10:00
Simple_Not
19999b28ad fixxed pipisa
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-16 01:51:52 +10:00
Simple_Not
e8190a500d fixxed pipisa
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-16 01:50:12 +10:00
Pavel_Durov
76d14126a1 -9 2 10
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-14 22:21:27 +03:00
Pavel_Durov
345168aa80 test
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 19:38:51 +03:00
Pavel_Durov
e2467803c5 back sendalarm
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 19:28:16 +03:00
Simple_Not
489a3304a4 HARD core
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 15:19:31 +10:00
Simple_Not
456d0619df another wut
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 14:39:20 +10:00
Simple_Not
360f8d4c55 another wut
Some checks reported errors
continuous-integration/drone/push Build was killed
2023-07-13 13:48:52 +10:00
Simple_Not
c39f1cde04 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 01:16:26 +10:00
Simple_Not
3f04de5cb1 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 01:00:50 +10:00
Simple_Not
53c48dbb44 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 00:40:55 +10:00
Simple_Not
361648f1c7 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 00:39:35 +10:00
Simple_Not
2de30513b2 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 00:31:00 +10:00
Simple_Not
f46ba32473 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 00:05:06 +10:00
Simple_Not
8d599c239b now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 00:03:16 +10:00
Simple_Not
9403350e15 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-13 00:01:25 +10:00
Simple_Not
9f27070585 now we counting
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 22:40:45 +10:00
Simple_Not
40927b95cc bring dick back.
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 22:33:36 +10:00
Simple_Not
460fccc6ab bring dick back.
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 22:07:03 +10:00
Simple_Not
1e4e6fa4d6 bring dick back.
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 22:00:17 +10:00
Simple_Not
c4ca3a98a1 bring dick back.
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 21:58:56 +10:00
Simple_Not
25e82e28d5 bring dick back.
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 21:58:19 +10:00
Simple_Not
e93d2c0ef7 bring dick back.
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-12 21:54:24 +10:00
Simple_Not
b673b43c93 no idia what i changed 2023-07-12 19:39:57 +10:00
Simple_Not
c02215574d no idia what i changed 2023-07-12 19:39:26 +10:00
Pavel_Durov
dea7805dff новый год сука
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-22 19:11:51 +03:00
Pavel_Durov
40abc7065d add poitive random for first user (69)
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-20 22:44:03 +03:00
Pavel_Durov
c02458b209 add poitive random for first user (69)
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-20 22:34:39 +03:00
fe64756bc4 #DICKBOT-1 Done
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-20 11:30:43 +10:00
6923cd2aa8 Update 'README.md'
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-20 11:28:25 +10:00
b73468c73f Update 'README.md'
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-20 11:24:38 +10:00
671c39be27 d
All checks were successful
continuous-integration/drone/push Build is passing
d
2023-06-20 11:23:56 +10:00
b9813528b1 Add 'README.md'
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-20 11:22:59 +10:00
293d90fb29 Update '.drone.yml'
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-19 08:57:33 -04:00
9432f67ada Update '.drone.yml'
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-19 08:57:15 -04:00
13 changed files with 325 additions and 170 deletions

View File

@@ -15,11 +15,18 @@ steps:
- name: test it first - name: test it first
commands: commands:
- /usr/bin/python3 -m py_compile bot.py - /usr/bin/python3 -m py_compile bot.py
- /usr/bin/python3 pipisa_functions/pipisa_time.py
- name: pull into the folduh - name: pull into the folduh
commands: commands:
- cd /usr/share/$DRONE_REPO_NAME - cd /usr/share/$DRONE_REPO_NAME
- git pull - su -c "git pull" jack
- chown -R jack:jack . #- chown -R jack:jack .
when:
branch:
- main
- name: restart systemd unit - name: restart systemd unit
commands: commands:
- systemctl restart jack_bot - systemctl restart jack_bot
when:
branch:
- main

13
README.md Normal file
View File

@@ -0,0 +1,13 @@
Пробуем проверять что-либо.
```mermaid
journey
title Пиписа
section Наш Чат
Оче больше пипис: 5: Алексей
Обычно большепенис: 3: Догоняющие
Скромный дик: 1: Отставшие
section Не наш чат
Не запустил: -1: Отставшие
Не крутил: 1: Отставшие
```

0
__init__.py Normal file
View File

8
bot.py
View File

@@ -1,20 +1,12 @@
import logging import logging
import graypy
from aiogram import executor from aiogram import executor
from create_bot import dp from create_bot import dp
import handlers import handlers
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(
level = logging.DEBUG,
handlers = [ graypy.GELFUDPHandler('localhost', 12201) ]
)
# pipisa.register_handlers_pipisa(dp) # pipisa.register_handlers_pipisa(dp)
# time_new_year.register_handlers_time(dp) # time_new_year.register_handlers_time(dp)

View File

@@ -1,4 +1,7 @@
from aiogram import Bot, Dispatcher from aiogram import Bot, Dispatcher
API_TOKEN = '5724991559:AAEuLvpLsgP6LHRGMSyFtQLlR5qPQUO4b_w' API_TOKEN = '5724991559:AAEuLvpLsgP6LHRGMSyFtQLlR5qPQUO4b_w'
bot = Bot(token=API_TOKEN, parse_mode="HTML") bot = Bot(token=API_TOKEN, parse_mode="HTML")
dp = Dispatcher(bot) dp = Dispatcher(bot)

View File

@@ -1,6 +1,6 @@
from handlers import pipisa from handlers import pipisa
from handlers import davinci from handlers import davinci
from handlers import time_new_year from handlers import time_new_year
from handlers import sendalarm from handlers import sendalarm
from handlers import start_help from handlers import start_help

View File

@@ -2,22 +2,26 @@ import openai
from aiogram import types, Dispatcher from aiogram import types, Dispatcher
from create_bot import dp, bot from create_bot import dp, bot
token = '5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc' token = '5947963644:AAF_GKgMmU5ovqMpc1KXIpcf4aN0JMyKPqc'
openai.api_key = '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' #openai.api_key = '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'
openai.api_key = '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'
@dp.message_handler() @dp.message_handler()
async def send(message: types.Message): async def send(message: types.Message):
if 'тупица' in message.text.lower(): if 'тупица' in message.text.lower():
## TODO уточнить остатки токенов и денег
response = openai.Completion.create( response = openai.Completion.create(
model="text-davinci-003", model="text-davinci-003",
prompt=message.text[7:], prompt=message.text[7:],
temperature=0.7, temperature=0.7,
max_tokens=1000, max_tokens=1000,
top_p=1.0, top_p=1.0,
frequency_penalty=0.0, frequency_penalty=0.0,
presence_penalty=0.6, presence_penalty=0.6,
stop=["сброс"] stop=["сброс"]
) )
await message.reply(response['choices'][0]['text']) await message.reply(response['choices'][0]['text'])

View File

@@ -1,179 +1,228 @@
from aiogram import types, Dispatcher from aiogram import types, Dispatcher
from sqlalchemy.orm.session import close_all_sessions #from sqlalchemy.orm.session import close_all_sessions
from create_bot import bot, dp from create_bot import bot, dp
from sqdb import user, session #from sqdb import user, session
import random import random
from random import randint from random import randint
import datetime import datetime
from dicktxt import ForReadDict from dicktxt import ForReadDict
from pipisa_functions import pipisa_time
#### https://docs.python-arango.com/en/main/
from arango import ArangoClient
@dp.message_handler(commands=["dick"]) @dp.message_handler(commands=["dick"])
async def up_dick(message: types.Message): async def up_dick(message: types.Message):
# рандомайзер #global size_change, dick_plus, dick_minus
numb = randint(-6,10)
global size_change, dick_plus, dick_minus
dick_plus = ('<b>вырос</b>', '<b>подрос</b>', '<b>привстал</b>') arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host')
dick_minus = ('<b>уменьшился</b>', '<b>откусила злая гадюка</b>', '<b>продали евреи, он стал дешевле</b>') pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527')
dicks_collection = pipisa_db.collection('dicks')
# рандомайзер
numb = randint(-9,10)
dick_plus = (
'<b>вырос</b>',
'<b>подрос</b>',
'<b>привстал</b>',
'<b>увеличился</b>',
'<b>преисполнился</b>'
)
dick_minus = (
'<b>неудачно потусил на сходке</b>',
'<b>уменьшился</b>',
'<b>откусила злая гадюка</b>',
'<b>продали евреи, он стал дешевле</b>',
'<b>схуднул</b>'
)
dick_stayed = (
'<b>продвинулся</b>',
'<b>наноуменьшился</b>',
'<b>зафиксировал прибыль</b>'
)
if numb > 0: if numb > 0:
size_change = random.choice(dick_plus) + '🚀' size_change = random.choice(dick_plus) + '🚀'
#if numb = 0 size_change = random.choice(const) TODO elif numb == 0:
else: size_change = random.choice(dick_minus) + '' size_change = random.choice(dick_stayed) + '🤨'
else:
size_change = random.choice(dick_minus) + ''
# работа с таблицей
try: try:
b = session.query(user).filter(user.user_id == message.from_user.id).first() #### Чекнуть есть ли юзер в базе
if b: candidate_cursor = dicks_collection.find(
last_time = b.datetimes {
now_time = datetime.datetime.now() 'user_id': message.from_user.id,
diff = now_time.day - last_time.day 'chat_id': message.chat.id
},
if abs(diff) <= 0: skip=0, limit=1488)
if candidate_cursor.count() > 0:
## Если есть то нарастить и отправить сообщение
user = candidate_cursor.pop()
if pipisa_time.rolltime(check_datetime=user['datetimes'], curr_time=datetime.datetime.now()):
# пришло время крутить!!
updetedDick = user["dick_size"] + numb
try: try:
current_dick = b.dick_size dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
metadata = dicks_collection.insert(
{
await bot.send_message(message.chat.id, f'@{message.from_user.username},🚫 вы уже крутили пипису, ее размер <b>{current_dick}</b> см! ') '_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
except: 'user_id': user['user_id'],
print('ошибка в if diff <=0') 'user_fullname': message.from_user.full_name,
session.rollback() 'dick_size': updetedDick,
finally: 'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
session.close_all() 'attempts': user['attempts'] + 1,
print('пользователь уже крутил') 'chat_id': message.chat.id
},
else: overwrite_mode='update'
try: )
a = session.query(user).filter(user.user_id == message.from_user.id).first() # запрос на поиск в таблице print(f'Успешно апдейтнули пипису @{message.from_user.username}')
updetedDick = a.dick_size = (a.dick_size + numb) except Exception as e2:
a.datetimes = datetime.datetime.now() print(f'ошибка в обновлении пиписы @{message.from_user.username}')
session.flush() print(e2)
session.commit() #обновляет запись
randomword = ForReadDict.RandomDick() randomword = ForReadDict.RandomDick()
await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш <em>{randomword}</em> {size_change}\
await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш <em>{randomword}</em> {size_change}\
на <b>{abs(numb)}</b> см!\n\ на <b>{abs(numb)}</b> см!\n\
Теперь он равен <b>{updetedDick}</b> см! ') Теперь он равен <b>{updetedDick}</b> см! ')
except: else:
session.rollback() await bot.send_message(message.chat.id, f'@{message.from_user.username},🚫 вы уже крутили пипису, ее размер <b>{user["dick_size"]}</b> см! ')
print('ошибка в обновлении пиписы')
finally:
session.close_all()
print('пиписа обновлена')
try:
metadata = dicks_collection.insert(
{
'_key': user['_key'], ### этот нужен чтобы апдейт прилетал тому же юзеру
'user_id': user['user_id'] ,
'user_fullname': message.from_user.full_name,
'dick_size': user['dick_size'] ,
'datetimes': user['datetimes'] ,
'attempts': user['attempts'] + 1,
'chat_id': message.chat.id
},
overwrite_mode='update'
)
print(f'Успешно апдейтнули попытку крутить пипису @{message.from_user.username}')
except Exception as e2:
print(f'ошибка в обновлении попытки крутить пипису @{message.from_user.username}')
print(e2)
else: print(f'пользователь @{message.from_user.username} уже крутил')
session.close()
try:
int_table = user(user_id = message.from_user.id, user_fullname = message.from_user.full_name, dick_size = numb, datetimes = datetime.datetime.now(),\
chat_id = message.chat.id)
session.add(int_table) else:
session.flush() ## если нету, то создать
session.commit()
session.close() try:
novenkiy = {
await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш писюн {size_change}\n\ 'user_id': message.from_user.id,
'user_fullname': message.from_user.full_name,
'dick_size': numb,
'datetimes': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'attempts': 1,
'chat_id': message.chat.id
}
metadata = dicks_collection.insert(novenkiy, overwrite_mode='update')
if numb > 0:
await bot.send_message(message.chat.id, f'@{message.from_user.username}, ваш писюн показал головку 🚀\n\
на <b>{abs(numb)}</b> см!\n\ на <b>{abs(numb)}</b> см!\n\
Теперь он равен <b>{numb}</b> см!') Теперь он равен <b>{numb}</b> см!')
except: else:
await bot.send_message(message.chat.id, f'@{message.from_user.username}, добро пожаловать в игру!🚀\n\
Ты стартуешь не с лучшей позиции, природа наградила тебя всего <b>{numb}</b> см 😬')
print(f'Успешно добавлен пользователь @{message.from_user.username}')
except Exception as e1:
print('ошибка в добавлении нового пользователя') print('ошибка в добавлении нового пользователя')
session.rollback() print(e1)
finally:
session.close_all()
print('Успешно добавлен пользователь') except Exception as e:
print('ошибка DB в /dick')
except: print(e)
session.rollback()
print('ошибка в основном коде')
finally:
session.close_all()
@dp.message_handler(commands=["topdick"]) @dp.message_handler(commands=["topdick"])
async def send_topchat(message: types.Message): async def send_topchat(message: types.Message):
arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host')
pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527')
dicks_collection = pipisa_db.collection('dicks')
try: try:
changechat_id = session.query(user).filter(user.user_id == message.from_user.id).first() dicks = dicks_collection.find({'chat_id': message.chat.id}, skip=0, limit=1100)
chats = message.chat.id dicks = [d for d in dicks]
if changechat_id.chat_id != chats: except Exception as e:
changechat_id.chat_id = chats print('ошибка DB в /topdick')
session.commit() print(e)
session.close()
else:
session.close()
top = session.query(user.user_fullname, user.dick_size).order_by(user.dick_size.desc()).filter(user.chat_id == chats).limit(10).all()
delimiter = ': '
# проверка на длину списка, если меньше limit, то: top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True)
dick_limit = min(len(top_dicks), 10)
top_dicks = top_dicks[:dick_limit]
dickos = ''
emo = ['🏆','🚀','🍆','🍌','🐍','🐎','🌭','🌶','👌','💩']
sizelen = len(top) if len(top_dicks) == 0:
if sizelen < 10: await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌')
lenminus = 10 - sizelen else:
top.extend(('-'*lenminus)) for i in range(len(top_dicks)):
await bot.send_message(message.chat.id, f'🏆Топ 10 бубылд чата🏆\n\n\ dickos += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n'
🚀 {delimiter.join(map(str, top[0]))}\n\ i += 1
💫 {delimiter.join(map(str, top[1]))}\n\
🍆 {delimiter.join(map(str, top[2]))}\n\
🍌 {delimiter.join(map(str, top[3]))}\n\
🐍 {delimiter.join(map(str, top[4]))}\n\
🐎 {delimiter.join(map(str, top[5]))}\n\
🌭 {delimiter.join(map(str, top[6]))}\n\
🌶 {delimiter.join(map(str, top[7]))}\n\
👌 {delimiter.join(map(str, top[8]))}\n\
💩 {delimiter.join(map(str, top[9]))}\n')
session.close()
# если все нормально и участников минимум 10
else: await bot.send_message(message.chat.id, '🏆Топ 10 бубылд чата🏆\n\n' + dickos)
await bot.send_message(message.chat.id, f'🏆Топ 10 бубылд чата🏆\n\n\
🚀 {delimiter.join(map(str, top[0]))}\n\
💫 {delimiter.join(map(str, top[1]))}\n\
🍆 {delimiter.join(map(str, top[2]))}\n\
🍌 {delimiter.join(map(str, top[3]))}\n\
🐍 {delimiter.join(map(str, top[4]))}\n\
🐎 {delimiter.join(map(str, top[5]))}\n\
🌭 {delimiter.join(map(str, top[6]))}\n\
🌶 {delimiter.join(map(str, top[7]))}\n\
👌 {delimiter.join(map(str, top[8]))}\n\
💩 {delimiter.join(map(str, top[9]))}\n')
except:
session.rollback()
print('ошибка в /topdick')
finally:
session.close_all()
@dp.message_handler(commands=["globaldick"]) @dp.message_handler(commands=["globaldick"])
async def send_global_top(message: types.Message): async def send_global_top(message: types.Message):
arango_client = ArangoClient(hosts='https://arango.guaranteedstruggle.host')
pipisa_db = arango_client.db('pipisa', username='root', password='stolendick527')
dicks_collection = pipisa_db.collection('dicks')
try: try:
top_chat = session.query(user.user_fullname, user.dick_size).order_by(user.dick_size.desc()).limit(10).all() dicks = dicks_collection.all( )
dicks = [d for d in dicks]
delimiter = ': ' except Exception as e:
print('ошибка DB в /glovaldick')
print(e)
await bot.send_message(message.chat.id, f'🏆Топ 10 пипис в мире🏆\n\n\
1. {delimiter.join(map(str, top_chat[0]))}\n\
2. {delimiter.join(map(str, top_chat[1]))}\n\
3. {delimiter.join(map(str, top_chat[2]))}\n\
4. {delimiter.join(map(str, top_chat[3]))}\n\
5. {delimiter.join(map(str, top_chat[4]))}\n\
6. {delimiter.join(map(str, top_chat[5]))}\n\
7. {delimiter.join(map(str, top_chat[6]))}\n\
8. {delimiter.join(map(str, top_chat[7]))}\n\
9. {delimiter.join(map(str, top_chat[8]))}\n\
10. {delimiter.join(map(str, top_chat[9]))}\n')
except:
session.rollback()
print('ошибка в /glovaldick')
finally:
session.close_all()
top_dicks = sorted(dicks, key=lambda dick: dick['dick_size'], reverse=True)
dick_limit = min(len(top_dicks), 10)
top_dicks = top_dicks[:dick_limit]
dickos = ''
emo = ['🏆','🚀','💫','🍆','🍌','🐍','🐎','🌭','🌶','👌']
# def register_handlers_pipisa(dp: Dispatcher): if len(top_dicks) == 0:
# dp.register_message_handler(up_dick) await bot.send_message(message.chat.id, '🍆 Никто ничего не нарастил! 🍌')
# dp.register_message_handler(send_topchat) else:
# dp.register_message_handler(send_global_top) for i in range(len(top_dicks)):
dickos += f' {emo[i]} {i+1}. {top_dicks[i]["user_fullname"]}: {top_dicks[i]["dick_size"]}см\n'
i += 1
await bot.send_message(message.chat.id, '🏆Топ 10 пипис в мире🏆\n\n' + dickos)

View File

@@ -12,11 +12,11 @@ async def sendall(message: types.Message):
if message.from_user.id == 226765676: if message.from_user.id == 226765676:
text = message.text[9:] text = message.text[9:]
try: try:
chats_id = session.query(user.chat_id).distinct() chats_id = -1001355646177
for row in chats_id:
try: try:
await bot.send_message(row[0], text) await bot.send_message(chats_id, text)
except: except:
print('вероятно бота нет в чате') print('вероятно бота нет в чате')
await bot.send_message(message.from_user.id, 'Сообщение успешно отправлено во все чаты') await bot.send_message(message.from_user.id, 'Сообщение успешно отправлено во все чаты')
except: except:

View File

@@ -4,7 +4,7 @@ import datetime
@dp.message_handler(commands=["time"]) @dp.message_handler(commands=["time"])
async def send_time(message: types.Message): async def send_time(message: types.Message):
new_year = datetime.datetime(2022, 12, 31) #дата нового года new_year = datetime.datetime(2024, 12, 31) #дата нового года
ct = datetime.datetime.now() #датавремя ct = datetime.datetime.now() #датавремя
cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г) cd = datetime.datetime.now().strftime("%d/%m/%Y") #дата (д,м,г)
ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера ct1 = ct+datetime.timedelta(hours=15) # +14 часов от сервера

View File

@@ -0,0 +1 @@
from . import pipisa_time

View File

@@ -0,0 +1,88 @@
import unittest
import datetime
def rolltime(check_datetime , curr_time=datetime.datetime.now()):
last_time = datetime.datetime.strptime(check_datetime, '%Y-%m-%d %H:%M:%S')
time_to_grow = curr_time.replace(hour=14, minute=8, second=8, microsecond=0) #+ datetime.timedelta(days=0)
timediff = (time_to_grow - last_time).total_seconds()
# print()
# print(f'\tlast_time : {last_time}')
# print(f'\ttime_to_grow : {time_to_grow}')
# print(f'\tcurr_time : {curr_time.strftime("%Y-%m-%d %H:%M:%S")}')
# print(f'\t\tsecs diff : {timediff}')
if timediff > 86400 or (curr_time > time_to_grow and last_time < time_to_grow):
return True
else:
return False
class TestPipisa(unittest.TestCase):
def test_very_long_ago(self):
self.assertEqual(rolltime('2021-10-11 23:44:00'), True, "Пиписа прокручена очень давно. Очевидный прокрут")
def test_just_after(self):
self.assertEqual(rolltime(
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
), False, "Попытка крутить когда старый прокрут был через 1 минуту после сегодняшнего обновления роллов. Фейл.")
def test_yesterdayroll(self):
self.assertEqual(
rolltime(
(
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(days=1)
).strftime('%Y-%m-%d %H:%M:%S'),
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0)
), True, "Крутилась вчера через минуту после обновления роллов. Должно пропускать ")
def test_hour_before_roll(self):
self.assertEqual(
rolltime(
(
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(hours=1)
).strftime('%Y-%m-%d %H:%M:%S'),
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0)
), True, "Крутилась последний раз за час до прокрута. Надо разрешать заново!")
def test_after_midnight(self):
self.assertEqual(
rolltime(
(
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(hours=14)
).strftime('%Y-%m-%d %H:%M:%S'),
datetime.datetime.now().replace(hour=0, minute=11, second=8, microsecond=0)
), False, "Где-то ночью прокручивается повторно. Фейл.")
def test_before_midnight(self):
self.assertEqual(
rolltime(
(
datetime.datetime.now().replace(hour=14, minute=9, second=8, microsecond=0) - datetime.timedelta(hours=15)
).strftime('%Y-%m-%d %H:%M:%S'),
datetime.datetime.now().replace(hour=0, minute=11, second=8, microsecond=0) - datetime.timedelta(hours=15)
), False, "Где-то ночью прокручивается повторно. Фейл.")
def test_somewhere_after(self):
self.assertEqual(
rolltime(
(
datetime.datetime.now().replace(hour=14, minute=26, second=8, microsecond=0)
).strftime('%Y-%m-%d %H:%M:%S'),
datetime.datetime.now().replace(hour=14, minute=27, second=8, microsecond=0)
), False, "Сегодня уже открутили а хотят ещё. Фейл.")
if __name__ == "__main__":
unittest.main(verbosity=2)

View File

@@ -1,4 +1,2 @@
aiogram aiogram
sqdb python-arango
sqlalchemy
graypy