简体   繁体   English

为什么“if in”语句不适用于discord.py?

[英]Why isn't the 'if in' statement working with discord.py?

I have the following code for a Discord bot I am working on:我有我正在处理的 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)

The 'members.txt' file contains: (members of my Discord server) “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

If I was to do the command v!ban UltimateDucc#9121 , it would return False instead of True , even though this value is present in the array.如果我要执行命令v!ban UltimateDucc#9121 ,它会返回False而不是True ,即使该值存在于数组中。

What I'm trying to achieve:我正在努力实现的目标:

Gather server members - Done收集服务器成员 -完成

Put into file - Done放入文件 -完成

Get input from user - Done从用户获取输入 -完成

Check if input is in file - Stuck检查输入是否在文件中 -卡住

Any help is appreciated.任何帮助表示赞赏。

f.read() will return a string with the contents of the file. f.read()将返回一个包含文件内容的字符串。
When you loop through it, i will be each character in that string.当您遍历它时, i将成为该字符串中的每个字符。

You should use list(f) or f.readlines() and strip the newline at the end instead您应该使用list(f)f.readlines()并在末尾f.readlines()换行符

See https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects for more information.有关更多信息,请参阅https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

Comments added for clarification but your base problem was that you were iterating over all of the characters in your loaded list from the file and checking if each one of them was equal to the string provided by the user.添加了注释以进行澄清,但您的基本问题是您正在从文件中迭代加载列表中的所有字符,并检查它们中的每一个是否等于用户提供的字符串。

@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")

Do not use this:不要使用这个:

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

Use this:用这个:

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

or或者

Use this:用这个:

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

In code block 1: Comparisons are done character by character.在代码块 1 中:逐个字符地进行比较。 You are comparing each character in the file to the string entered by user.您正在将文件中的每个字符与用户输入的字符串进行比较。

In code block 2: Python looks for a substring the in the given string.在代码块 2 中:Python 在给定字符串中查找子字符串 。 ie: It'll return True if the string entered by the user is present in the content of the file.即:如果用户输入的字符串存在于文件内容中,它将返回 True。

In code block 3: Split the content of the file up line by line and store each entry in an array.在代码块 3 中:将文件内容逐行拆分,并将每个条目存储在一个数组中。 Then look if the string entered by the user is there in this array.然后查看用户输入的字符串是否在这个数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM