RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-409446

piece0f's questions

Martin Hope
piece0f
Asked: 2022-06-12 00:33:32 +0000 UTC

如何在读取方法期间摆脱文件中的转义转换?

  • 1

有一个 .txt 文件,其中包含一个带有转义的字符串\n。当在 python 中用 读取这个文件时,read()这个字符被转换为使用时s.encode('unicode_escape')(即\n变为\\\\n,解码时变为\\n)。我需要一种方法来阻止或扭转这种转变。

with open('../quotes/to_add.txt', 'r', encoding="UTF-8") as q:
    q = q.read().splitlines()

文件示例:

Ну вот идут буковки буковки и тут хоп:\n- Начался диалог\n- Закончился

我需要在阅读后在屏幕上显示:

Ну вот идут буковки буковки и тут хоп:
- Начался диалог
- Закончился
python
  • 1 个回答
  • 10 Views
Martin Hope
piece0f
Asked: 2022-04-04 18:11:33 +0000 UTC

lru_cache 和清除缓存

  • 3

有一个电报机器人根据时间表发送报价。添加到其lru_cache通过functools.

结果,用户收到了 3 次相同的报价(在不同的时间),尽管cache_clear()我在每次邮寄后都收到了。引号取自 MongoDB,这是我想要缓存的时刻,这样它就不会花一秒钟的时间。

class Quote:
    @lru_cache(maxsize=19)
    def check(self, user: str, check=True) -> dict:
        """Checks for quote available for {user}"""
        est_quotes = self.db.estimated_document_count()
        if self.db.count_documents({"Users": user}) >= est_quotes - 1:
            # removes user id from DB if there is no more available quotes for user
            self.db.update_many({"Users": user}, {"$pull": {"Users": user}})
        all_quotes = self.db.find({})
        while True:
            quote = all_quotes[random.randint(0, est_quotes - 1)]
            if not check:
                # if check for available is not required return random quote
                return quote
            if user in quote["Users"]:
                continue
            required_quote = quote
            self.db.update_one({"Quote": quote["Quote"]}, {"$push": {"Users": user}})
            return required_quote

    def random(self, user, checking=False):
        """ Sends random quote for user.
            If checking == False, it does not check for the presence of id in the database.
        """
        quo = self.check(user, check=checking)
        keyboard = types.InlineKeyboardMarkup()
        key_book = types.InlineKeyboardButton(text='📖', callback_data='book', url=quo["URL"])
        keyboard.add(key_book)
        #   key_like = types.InlineKeyboardButton(text='Нет', callback_data='no')
        #   keyboard.add(key_like)
        bot.send_message(user,
                         text=f'<i>{quo["Quote"]}\n</i>\n<b>{quo["Book"]}</b>\n#{quo["Author"]}',
                         parse_mode='HTML', reply_markup=keyboard)

    def randoms(self, group: int):
        """Sends random quote for users who aren't in 'stopped' list"""
        start_time = time.time()
        counter = 0
        with open(f'users{group}', 'r') as users_r:
            r = users_r.read().splitlines()
        print("=================================")
        for user_id in r:
            if user_id in self.stopped:
                continue
            try:
                self.random(str(user_id), True)
                print(f"Latency #{counter}: {str(time.time() - start_time)[:4]} seconds")
            except telebot.apihelper.ApiTelegramException as e:
                print(f"Bad ID ({user_id}):", e)
            except Exception as e:
                print(e)
            finally:
                counter += 1
        self.check.cache_clear()

很可能,我只是不太了解缓存的方式和内容,但我请您为我的问题提出最佳解决方案。

python
  • 1 个回答
  • 10 Views
Martin Hope
piece0f
Asked: 2022-02-19 23:19:13 +0000 UTC

单击按钮时如何使功能停止?

  • 1
@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    keyboard = types.InlineKeyboardMarkup()
    key_cancel = types.InlineKeyboardButton(text='Отменить', callback_data='cancel')
    keyboard.add(key_cancel)
    if call.data == "report":
        bot.send_message(call.message.chat.id,
                         '<i>Опишите проблему, Ваше сообщение будет доставлено администрации и принято на рассмотрение!\n</i>',
                         parse_mode='HTML', reply_markup=keyboard)
        if call.data == 'cancel':
            bot.send_message(call.message.chat.id,
                             '<b><i>Отменено!</i></b>',
                             parse_mode='HTML')
        else:
            bot.register_next_step_handler(call.message, report_send)
    elif call.data == "support":
        bot.send_message(call.message.chat.id,
                         '<i>Опишите Вашу идею, сообщение будет доставлено администрации и принято на рассмотрение!\n</i>',
                         parse_mode='HTML', reply_markup=keyboard)
        if call.data == 'cancel':
            bot.send_message(call.message.chat.id,
                             '<b><i>Отменено!</i></b>',
                             parse_mode='HTML')
        else:
            bot.register_next_step_handler(call.message, support_send)

我需要当按钮被按下时,cancel函数(support_send() или report_send())的执行停止,或者在用户写消息之前它根本不启动。使用异步库是可能的,但不可取。

python
  • 1 个回答
  • 10 Views
Martin Hope
piece0f
Asked: 2021-12-01 19:46:01 +0000 UTC

如何让它在 try/except 块之后只抛出一个异常?

  • 0

有这样一个“迭代器”:

class MyIterator():
    def __init__(self, lst):
        self.lst = lst
        self.counter = 0

    def __next__(self):
        try:
            z = self.lst[self.counter]
            self.counter += 2
            return z
        except:
            raise StopIteration

出现错误后,它会输出以下内容:

Traceback (most recent call last):
  File "C:/BookBot/test.py", line 10, in __next__
    z = self.lst[self.counter]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/BookBot/test.py", line 22, in <module>
    print(next(x))
  File "C:/BookBot/test.py", line 14, in __next__
    raise StopIteration
StopIteration

问题:如何做到这一点,只有StopIteration,有可能做到这一点吗?

python
  • 1 个回答
  • 10 Views
Martin Hope
piece0f
Asked: 2021-10-23 22:41:00 +0000 UTC

角色的自动配置不起作用 | 不和谐.py

  • 1

我试图找出问题所在,但我并没有真正找到关于角色自动分配错误的任何内容。它不会给控制台任何错误,它只是不响应用户进入服务器。

@bot.event
async def on_member_join(member):
    new = discord.utils.get(member.guild.roles, id=767446695294140426)
    channel = discord.utils.get(member.channel, id=767470344189247590)
    await member.add_roles(new)
    await channel.send(f"{member.mention} joined to channel!")
python
  • 2 个回答
  • 10 Views
Martin Hope
piece0f
Asked: 2021-10-21 01:49:48 +0000 UTC

不和谐.py | 如何找出编写命令的人的角色ID

  • 0

在这段代码中,我需要确定给定的角色 ID 是否在作者角色列表中。角色 ID - 767450270888099910

@bot.command()
async def report(ctx, player: discord.Member, *args):
    author = ctx.message.author
    if 767450270888099910 in author.roles:
        await ctx.send('Предателям не давали право открывать рот! Скажи спасибо что ты можешь остаться на сервере...')
        return True
discord
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5