【问题标题】:Why isn't the 'if in' statement working with discord.py?为什么'if in' 语句不能与 discord.py 一起使用?
【发布时间】:2020-05-06 15:51:37
【问题描述】:

我正在开发的 Discord 机器人有以下代码:

import discord
import random 
from discord.ext import commands, tasks
import os
import time
import asyncio
import re
import urllib.request
import json
from apiclient.discovery import build
from itertools import product, cycle
from discord.ext.tasks import loop

client = commands.Bot(command_prefix =  'v!', description='fff', case_insensitive=True)

token = 'REDEACTED'
client.remove_command("help")

@client.command(pass_context=True)
async def Ban(ctx):

    members = []

    a = (ctx.author)
    print(a)

    m = (ctx.message.content)

    m = m.replace("v!ban ", '')
    print(m)

    with open('members.txt', 'w'): pass

#    print(members)
    for member in ctx.guild.members:

        with open('members.txt', 'a', encoding = "UTF-8") as f:
            f.writelines(str(member) + '\n')

    with open('members.txt', 'r', encoding = "UTF-8") as f:
        members = f.read()

    for i in members:
        if i == m:
            print('True')
        else:
            print("False")

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity = discord.Game("v!help"))

client.run(token)

“members.txt”文件包含:(我的 Discord 服务器的成员)

kurt#6396
galen#2172
xXDEFECTMEXx#0598
xx_kyrah.w#2995
lmao.com#5953
skyanite#1725
Gilly#5865
chef shaq#3889
mariokuhl.RS#0101
UltimateDucc#9121
xSaltyOne#9450
Jacobs Kid#0771
Alex L#7988
✪ csw ✪#0115
smithers#4004
Little5avage#8028
FaZe_Eric#9627
Unib_Rovodkalan#8661

ARX6.#5773
The Bomb#3693

如果我要执行命令v!ban UltimateDucc#9121,它将返回False 而不是True,即使该值存在于数组中。

我想要达到的目标:

收集服务器成员 - 完成

放入文件 - 完成

从用户那里获取输入 - 完成

检查输入是否在文件中 - 卡住

感谢任何帮助。

【问题讨论】:

  • 我在任何地方都看不到if... in。不过我很好奇,with open('members.txt', 'w'): pass 是干什么用的?
  • 这里指的是for i in members:
  • 该行也清除了文本文件。
  • 你的意思是if i in m:
  • 是的,'m' 是用户名

标签: python if-statement discord discord.py


【解决方案1】:

f.read() 将返回一个包含文件内容的字符串。
当您遍历它时,i 将是该字符串中的每个字符。

您应该使用list(f)f.readlines() 并在末尾去掉换行符

更多信息请参见https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

【讨论】:

    【解决方案2】:

    为澄清添加了注释,但您的基本问题是您正在从文件中迭代加载列表中的所有字符并检查每个字符是否 等于用户提供的字符串。

    @client.command(pass_context=True)
    async def Ban(ctx):
    
        members = []
    
        a = (ctx.author)
        print(a)
    
        m = (ctx.message.content)
    
        m = m.replace("v!ban ", '')
        print(m)
    
        with open('members.txt', 'w'): pass
    
        # I swapped the order here because otherwise the file gets opened each iteration
        with open('members.txt', 'a', encoding = "UTF-8") as f:
            for member in ctx.guild.members:
                f.write(str(member) + '\n') # you don't have to use writelines here because you are only writing a single line
    
        with open('members.txt', 'r', encoding = "UTF-8") as f:
            members = f.read().split('\n') # we want a list of members, not a string containing all of them
    
        # we can just use the "in" operator here, it checks if our string is in the loaded list
        if m in members:
            print('True')
        else:
            print("False")
    

    【讨论】:

      【解决方案3】:

      不要使用这个:

      # code block 1
      for i in members:
          if i == m:
              print('True')
          else:
              print("False")
      

      使用这个:

      # code block 2
      if i in members:
          print('true')
      else:
          print('false')
      

      使用这个:

      # code block 3 
      x = members.split('\n')
      if i in members:
          print('true')
      else:
          print('false')
      

      在代码块 1 中: 比较是逐个字符进行的。 您正在将文件中的每个字符与用户输入的字符串进行比较。

      在代码块 2 中: Python 在给定字符串中查找子字符串。 即:如果用户输入的字符串存在于文件内容中,它将返回 True。

      在代码块 3 中: 逐行拆分文件的内容并将每个条目存储在一个数组中。然后查看用户输入的字符串是否在这个数组中。

      【讨论】:

      • 我没有投反对票,但我猜反对票是因为您发布了代码而没有解释。您的修改在一定程度上解决了这个问题。
      • @byxor 我明白了,但他们可以通过发表评论让我知道。
      猜你喜欢
      • 2021-09-18
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      相关资源
      最近更新 更多