I want to send "I have it" when "xlsx A1~A500" matches the user ID

huangapple go评论64阅读模式
英文:

I want to send "I have it" when "xlsx A1~A500" matches the user ID

问题

import discord, openpyxl
client = discord.Client()

@client.event
async def on_message(message):
    if message.content.startswith("$text"):
        wb = openpyxl.load_workbook('test.xlsx')
        sheet = wb['Sheet1']
        for i in range(2, 501):
            heng = sheet[f"A{i}"].value
            if heng == f"#{message.author.id}":
                await message.channel.send(f"{i}: 我已经有了。")
                break  # <---问题所在
            else:
                wb = openpyxl.load_workbook('test.xlsx')
                sheet = wb['Sheet1']
                next_row = sheet.max_row + 1
                sheet[f"A{next_row}"].value = f"#{message.author.id}"
                next_row += 1
                wb.save('test.xlsx')
                await message.channel.send("信息已生成")
                break

也许是因为 "if" 下面的 "break" 语句,导致循环语句被中断,因此只有 "A2" 的文件被识别。

我希望在 "A1~A500" 与用户ID匹配时发送 "我已经有了"。

英文:
import discord,openpyxl
client = discord.Client()
@client.event
async def on_message(message):
    if message.content.startswith(&quot;$text&quot;):     
        wb = openpyxl.load_workbook(&#39;test.xlsx&#39;)
        sheet = wb[&#39;Sheet1&#39;]
        for i in range(2, 501):
            heng = sheet[f&quot;A{i}&quot;].value
            if heng == f&quot;#{message.author.id}&quot;: 
                await message.channel.send(f&quot;{i}: I already have it.&quot;)
                break # &lt;--problem 
            else:
                wb = openpyxl.load_workbook(&#39;test.xlsx&#39;)
                sheet = wb[&#39;Sheet1&#39;]        
                next_row = sheet.max_row + 1
                sheet[f&quot;A{next_row}&quot;].value = f&quot;#{message.author.id}&quot;
                next_row += 1
                wb.save(&#39;test.xlsx&#39;)
                await message.channel.send(&quot;Information has been generated&quot;)
                break

Maybe because of the "break" under "if", the repeat statement is interrupted, so only the xlsx file "A2" is recognized.

I want to send "I have it" when "A1~A500" matches the user ID.

答案1

得分: 0

我认为你的脚本存在一些基本问题。

for循环的第一次迭代中,i的值是2。我们检查A2是否等于作者的用户ID,如果相等,我们会发布一条消息说是,并退出。如果不相等,我们会自动将该ID添加到表的末尾。我在本地使用我的test.xlsx进行了测试,它只在A1中添加了一个列名,而max_row始终为2(下一个空单元格),因此通过在其上加1,你将在A3插入名称。所以下次发送消息时,我们检查A2,由于它不存在,我们决定再次插入名称 - 但这次在A4。如此反复进行。

因此,我对循环进行了一些改进:

import discord
import openpyxl

client = discord.Client()
@client.event
async def on_message(message):
    if message.content.startswith("$text"): 
        author_id = message.author.id
        wb = openpyxl.load_workbook('test.xlsx')
        sheet = wb['Sheet1']
        for i in range(2, 501):
            cell_value = sheet[f"A{i}"].value
            if not cell_value:
                # 单元格为空!
                # 这是数据的末尾吗?
                # 在这里插入用户
                sheet[f"A{i}"] = f"#{author_id}"
                wb.save('test.xlsx')
                await message.channel.send(f"已插入 {author_id} 用户在 A{i}")
                break
            elif cell_value == f"#{author_id}": 
                # 找到包含我们数据的单元格
                await message.channel.send(f"{i}: 我已经有了。")
                break
            else:       
                # else语句在这里基本上无关紧要,但为了演示而保留
                # cell_value等于不同的用户名
                continue

这个工作效果更好:

  • 2开始,我们查看列A中的所有行
  • 如果单元格为空 - 这假定这是数据的末尾,后面没有内容;所以我们在这里插入作者的ID
  • 如果单元格不为空 - 检查它是否等于作者的ID。如果是,那么我们找到了它 - 万岁!
  • 否则,检查下一行

我在本地测试了这个代码,它似乎能够实现你想要的功能。

仍然有一些改进可以做:

  • 如果你有超过~500个唯一用户,那么可能永远找不到用户ID,因为它会达到range的末尾,如果所有其他单元格都包含其他用户的数据
  • 假定空单元格意味着列表的末尾 - 但这可能并不一定是情况。
英文:

I think there's a few fundamental issues with your script.

On the first iteration of the for loop, i is 2. We check that A2 is equal to the author's user ID and if it is we post a message saying it is and exit. If it isn't, then we automatically add that ID to the end of the sheet. I tested this locally with my own test.xlsx that only add a column name in A1 and max_row was always 2 (the next empty cell) and so by adding one to that - you're inserting the name at A3. So the next time you send a message, we check A2, and as it's not there we decide to insert the name again - but this time at A4. And so on and so forth.

So I've made some improvements on the loop:

import discord
import openpyxl

client = discord.Client()
@client.event
async def on_message(message):
    if message.content.startswith(&quot;$text&quot;): 
        author_id = message.author.id
        wb = openpyxl.load_workbook(&#39;test.xlsx&#39;)
        sheet = wb[&#39;Sheet1&#39;]
        for i in range(2, 501):
            heng = sheet[f&quot;A{i}&quot;].value
            if not heng:
                # the cell is empty!
                # is this the end of the data?
                # insert user here
                sheet[f&quot;A{i}&quot;] = f&quot;#{author_id}&quot;
                wb.save(&#39;test.xlsx&#39;)
                await message.channel.send(f&quot;Inserted {author_id} user at A{i}&quot;)
                break
            elif heng == f&quot;#{author_id}&quot;: 
                # found a cell that contains our data
                await message.channel.send(f&quot;{i}: I already have it.&quot;)
                break
            else:       
                # else statement is largely irrelevant here - but keeping for demonstration
                # heng is equal to a different username
                continue

This works a bit better:

  • starting at 2, we're looking at all the rows in column A
  • if the cell is empty - this assumes this is the end of the data and there's nothing after it; so we insert our author ID here
  • if the cell isn't empty - check it's equal to our author ID. If it is; then we found it - hurray!
  • otherwise, check the next row down

I've tested this locally and this seems to do what you want it do now.

There are still some improvements to be made:

  • if you had over ~500 unique users, then it's possible it would never find the user ID as it would reach the end of the range if all the other cells have other users in them
  • assumes an empty cell means end of the list - but might not necessarily be the case

huangapple
  • 本文由 发表于 2023年1月6日 14:51:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75027820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定