1

So, Im coding a telegram bot using aiogram. His job is to get the news from parser through function trans_news then process it through ChatGPT and then send the processed news to admins pm. Then admin can - delete, edit or post it. If button "post" pressed the bot will send the message to a channel.

THE PROBLEM IS:

Whenever a bot gets news its fine, but when more is being sent without admin doing something to the first one, its being overwritten by a new one. I need something like a queue, so they wont overwrite each other.

dp = Dispatcher(bot, storage=storage)

msg = types.Message

data = {}


class AdmState(StatesGroup):
    redacting = State()
    afk = State()


@dp.message_handler(commands=['start'], state="*")
async def on_start(msg: msg):
    if str(msg.from_user.id) == admin_id:
        await bot.send_message(admin_id, 'Вы авторизованы как админ, добро пожаловать!')
        dicto = {
            "topic":"PA approves new bridge and junction at Manoel Island",
            "body":"""The Planning Authority board has approved the construction of a new bridge linking 
            the Gzira promenade to Manoel Island, as well as a new junction consisting of a roundabout. 
            The project consists of the construction of a vehicular and pedestrian bridge and the formation 
            of a new roundabout on Triq ix-Xatt and Triq William Reid, replacing the current junction, 
            which links Gzira with Manoel Island. The works include the construction of a gateway piazza 
            and quayside and the construction.""",
            "pic":"https://cdn-attachments.timesofmalta.com/01a8df8397080c89230fe933c4fa8e95c2d64c20-1691060877-27a82c39-630x420.jpg"
            }
        await trans_news(dicto)

    else:
        await bot.send_message(msg.from_user.id, 'Ваш ID не распознан как системный.')

async def trans_news(dicto: dict):
    instruction = 'Paraphrase the news while maintaining its meaning. You cant make a response that is longer than 900 symbols. its illegal!!!'
    
    body_prompt = f"{instruction}.\n{dicto[f'body']}"
    topic_prompt = f"{instruction}.\n{dicto[f'topic']}"


    response_topic = openai.ChatCompletion.create( 
        model="gpt-3.5-turbo",
        messages=[{"role": "system", "content": topic_prompt}],
        max_tokens=500,
        temperature=0.8,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )

    
    response_text_topic = response_topic.choices[0].message['content'].strip()

    response_body = openai.ChatCompletion.create( 
        model="gpt-3.5-turbo",
        messages=[{"role": "system", "content": body_prompt}],
        max_tokens=3000,
        temperature=0.8,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    response_text_body = response_body.choices[0].message['content'].strip()
    
    await check_news(response_text_body, response_text_topic, dicto[f"pic_{id}"])

async def check_news(resp_body, resp_top, pic):
    msg_id = await bot.send_photo(admin_id, pic, f"<b>{resp_top}</b>\n\n{resp_body}", reply_markup=nav.admMenu, parse_mode=ParseMode.HTML)
    global data
    data = {"topic": resp_top, "body": resp_body, "pic": pic, "msg_id":msg_id["message_id"]}




@dp.callback_query_handler(text='btnYPRSD', state=AdmState.on_news)
async def post_news(msg):
    global data
    await bot.delete_message(admin_id,  message_id=data["msg_id"])
    await bot.send_photo(channel_id, data["pic"], f"{data['topic']}\n\n{data['body']}")
    data = []
    print("posting")
    await AdmState.afk.set()

@dp.callback_query_handler(text='btnDeletePRSD', state=AdmState.on_news)
async def del_new(msg):
    global data
    await bot.delete_message(admin_id,  data['msg_id'])
    data = []
    await AdmState.afk.set()

@dp.callback_query_handler(text='btnRedactPRSD', state=AdmState.on_news)
async def red_news(msg):
    global data
    msg_id = await bot.send_message(admin_id, 'Отправьте измененный текст сообщения.')
    
    await AdmState.redacting.set()



@dp.message_handler(state=AdmState.redacting)  
async def red_txt(msg):
    global data
    data["body"] = msg['text']
    await AdmState.afk.set()
    await check_news(data["body"], data["topic"], data["pic"])


if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

For testing the news is written to dicto.

I tried using dictionaries with random id's, but it seems like i dont have enough iq to make it work as intendet.

GonnaBeDev
  • 13
  • 3

1 Answers1

0

So, i figured it out using Queue module.

GonnaBeDev
  • 13
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 10 '23 at 04:24