Heroku multiple accounts database, fixes

pull/1/head
hikariatama 2022-05-30 20:58:20 +00:00
parent e99caceb63
commit 1e7c0201d9
7 changed files with 34 additions and 19 deletions

View File

@ -68,8 +68,8 @@ class Database(dict):
await asyncio.sleep(5) await asyncio.sleep(5)
self._postgre.execute( self._postgre.execute(
"DELETE FROM hikka WHERE id = 1; INSERT INTO hikka (id, data) VALUES (1, %s);", "DELETE FROM hikka WHERE id = %s; INSERT INTO hikka (id, data) VALUES (%s, %s);",
(json.dumps(self),), (self._client._tg_id, self._client._tg_id, json.dumps(self)),
) )
self._postgre.connection.commit() self._postgre.connection.commit()
@ -152,7 +152,10 @@ class Database(dict):
"""Read database and stores it in self""" """Read database and stores it in self"""
if self._postgre: if self._postgre:
try: try:
self._postgre.execute("SELECT data FROM hikka") self._postgre.execute(
"SELECT data FROM hikka WHERE id=%s;",
(self._client._tg_id,),
)
self.update(**json.loads(self._postgre.fetchall()[0][0])) self.update(**json.loads(self._postgre.fetchall()[0][0]))
except Exception: except Exception:
logger.exception("Error reading postgresql database") logger.exception("Error reading postgresql database")

View File

@ -24,7 +24,7 @@ def publish(
app, config = get_app(key, api_token, create_new) app, config = get_app(key, api_token, create_new)
# Will be configured later in app # Will be configured later in app
config["HIKKA_SESSION"] = "None" config["hikka_session"] = None
config["heroku_api_token"] = key config["heroku_api_token"] = key
if api_token is not None: if api_token is not None:

View File

@ -328,8 +328,8 @@ class Hikka:
) )
] ]
if os.environ.get("HIKKA_SESSION") not in {None, "None"}: if os.environ.get("hikka_session"):
self.sessions += [StringSession(os.environ.get("HIKKA_SESSION"))] self.sessions += [StringSession(os.environ.get("hikka_session"))]
def _get_api_token(self): def _get_api_token(self):
"""Get API Token from disk or environment""" """Get API Token from disk or environment"""
@ -413,7 +413,8 @@ class Hikka:
if "DYNO" not in os.environ: if "DYNO" not in os.environ:
session.save() session.save()
else: else:
os.environ["HIKKA_SESSION"] = session.save() config = heroku.get_app(os.environ["heroku_api_token"])[1]
config["hikka_session"] = session.save()
client.session = session client.session = session
# Set db attribute to this client in order to save # Set db attribute to this client in order to save

View File

@ -413,8 +413,8 @@ class TestMod(loader.Module):
self._logchat = int(f"-100{chat.id}") self._logchat = int(f"-100{chat.id}")
if not is_new or all( if not is_new and any(
participant.id != self.inline.bot_id participant.id == self.inline.bot_id
for participant in (await self._client.get_participants(chat, limit=3)) for participant in (await self._client.get_participants(chat, limit=3))
): ):
logging.getLogger().handlers[0].install_tg_log(self) logging.getLogger().handlers[0].install_tg_log(self)

View File

@ -41,7 +41,7 @@ from telethon.tl.functions.messages import (
) )
from telethon.tl.types import DialogFilter, Message from telethon.tl.types import DialogFilter, Message
from .. import loader, utils from .. import loader, utils, heroku
from ..inline.types import InlineCall from ..inline.types import InlineCall
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -177,6 +177,11 @@ class UpdaterMod(loader.Module):
os.system("lavhost restart") os.system("lavhost restart")
return return
if "DYNO" in os.environ:
app = heroku.get_app(os.environ["heroku_api_token"])[0]
app.dynos()[0].restart()
return
atexit.register(restart, *sys.argv[1:]) atexit.register(restart, *sys.argv[1:])
handler = logging.getLogger().handlers[0] handler = logging.getLogger().handlers[0]
handler.setLevel(logging.CRITICAL) handler.setLevel(logging.CRITICAL)
@ -415,7 +420,7 @@ class UpdaterMod(loader.Module):
self.set("do_not_create", True) self.set("do_not_create", True)
async def update_complete(self, client: "TelegramClient"): # noqa: F821 async def update_complete(self, client: "TelegramClient"): # type: ignore
logger.debug("Self update successful! Edit message") logger.debug("Self update successful! Edit message")
start = self.get("restart_ts") start = self.get("restart_ts")
try: try:

View File

@ -42,7 +42,7 @@ import re
import requests import requests
import time import time
from .. import utils, main, database from .. import utils, main, database, heroku
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from telethon.errors.rpcerrorlist import YouBlockedUserError from telethon.errors.rpcerrorlist import YouBlockedUserError
@ -116,7 +116,7 @@ class Web:
async def _check_bot( async def _check_bot(
self, self,
client: "TelegramClient", # noqa: F821 client: "TelegramClient", # type: ignore
username: str, username: str,
) -> bool: ) -> bool:
async with client.conversation("@BotFather", exclusive=False) as conv: async with client.conversation("@BotFather", exclusive=False) as conv:
@ -191,11 +191,16 @@ class Web:
): ):
return web.Response(status=400) return web.Response(status=400)
if "DYNO" not in os.environ:
with open( with open(
os.path.join(self.data_root or DATA_DIR, "api_token.txt"), os.path.join(self.data_root or DATA_DIR, "api_token.txt"),
"w", "w",
) as f: ) as f:
f.write(api_id + "\n" + api_hash) f.write(api_id + "\n" + api_hash)
else:
config = heroku.get_app(os.environ["heroku_api_token"])[1]
config["api_id"] = api_id
config["api_hash"] = api_hash
self.api_token = collections.namedtuple("api_token", ("ID", "HASH"))( self.api_token = collections.namedtuple("api_token", ("ID", "HASH"))(
api_id, api_id,

View File

@ -9,6 +9,7 @@ requests==2.27.1
aiogram==2.19 aiogram==2.19
websockets==10.2 websockets==10.2
grapheme==0.6.0 grapheme==0.6.0
heroku3 heroku3==5.1.4
psycopg2-binary==2.9.3
# Python 3.8+ # Python 3.8+