如何防止不和谐的机器人随机中断

时间:2019-02-21 22:20:33

标签: python discord discord.py

我有一个不和谐的机器人,它在被调用时运行一个设置程序。在程序中出现任何错误之后,如果在此之后再次调用它,它将随机保留上次使用的值或响应自身再次破坏代码。这是代码。

from planetlists import planet_cap,planet_lvl,transfer,temp,credit_per_hour,planet_cost,max_levels_planet
import time
import discord
import asyncio

style.use("fivethirtyeight")

client = discord.Client()
TOKEN = '-----------------'  


async def get_input_of_type(func):
    while True:
        try:
            msg = await client.wait_for('message')
            return func(msg.content)
        except ValueError:
            continue

@client.event  # event decorator/wrapper
async def on_ready():
    global sentdex_guild
    print(f"We have logged in as {client.user}")


@client.event
async def on_message(message):
    global sentdex_guild

    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")


    if "hadescalc.logout()" == message.content.lower():
        await client.close()

    elif "hadescalc.planet()" == message.content.lower():
        await message.channel.send("What is the first number?")
        firstnum = await get_input_of_type(int)
        firstnum = firstnum + 3
        await message.channel.send("What is the second number?")
        secondnum = await get_input_of_type(int)
        await message.channel.send(f"{firstnum} + {secondnum} = {firstnum+secondnum}")


    elif message.content.startswith('$planet_cap'):
        channel = message.channel
        try:
            class Planet:
                def __init__(self,level = 0,storage = 0,credit_per_hour = 0,cost = 0,types = 'desert',tier = 1):
                    self.level = level
                    self.storage = storage
                    self.credit_per_hour = credit_per_hour
                    self.cost = cost
                    self.types = types
                    self.tier = tier

                def __str__ (self):
                    return ('level: '+ self.level + ', storage cap: ' + self.storage + ', credits per hour: ' + self.credit_per_hour + ', cost to upgrade: ' + self.cost + ', Planet type: ' + self.types + ', planet tier: ' + self.tier)

                def set_planet_lvl(self,level):
                    self.level = level
                def get_planet_lvl(self):
                    return(self.level)
                def set_planet_cost(self,cost):
                    self.cost = cost
                def get_planet_cost(self):
                    return(self.cost)
                def set_planet_storage(self,storage):
                    self.storage = storage
                def get_planet_storage(self):
                    return(self.storage)
                def set_planet_credit_per_hour(self,credit_per_hour):
                    self.credit_per_hour = credit_per_hour
                def get_planet_credit_per_hour(self):
                    return(self.credit_per_hour)
                def get_planet_types(self):
                    return(self.types)
                def get_planet_tier(self):
                    return(self.tier)

            planet_list = {}


            await channel.send('how many planets do you have?')
            number = await get_input_of_type(int)
            await channel.send('for planet type, choose from desert,fire,water,terran,gas, and ice\n   ')
            await channel.send('for planet tier you can only do the folowing...\n \ndesert- 1,3,4\nfire- 1,3,4\nwater- 1,3,4\nterrran- 1,3,4\ngas- 2,4\nice- 4')
            for i in range(number):  
                await channel.send('level for the {} planet: '.format(i+1))
                levels = await get_input_of_type(str)
                print(levels)
                credit_cap = planet_cap(levels)
                print(credit_cap)

                await channel.send('planet type for the {} planet: '.format(i+1))
                planet_type = await get_input_of_type(str)

                await channel.send('planet tier for the {} planet: '.format(i+1))

                teirlvl = await get_input_of_type(str)
                credits_per_hour = credit_per_hour(planet_type,levels,teirlvl)

                cost = planet_cost(levels)

                planet_list[i] = (Planet(levels,credit_cap,credits_per_hour,cost,planet_type,teirlvl))

            orig_planet_lvl = []
            for i in planet_list:
                orig_planet_lvl.append(planet_list[i].get_planet_lvl())

            cost_list = []
            increase_in_cap = []
            increase_in_income = []
            decider = []
            temp_planets = planet_list.copy()

            current_storage = 0


            for i in temp_planets:
                storage = int(temp_planets[i].get_planet_storage())
                print(storage)
                current_storage += storage

            await channel.send(('Your starting storage is: ',current_storage))

            await channel.send('what is your credit cap goal: ')

            cap_goal = await get_input_of_type(int)

            max_levels = []

            for i in planet_list:
                max_levels.append(max_levels_planet(temp_planets[i].get_planet_types(),temp_planets[i].get_planet_tier()))

            while cap_goal >= current_storage:

                for i in temp_planets:

                    storage = temp_planets[i].get_planet_storage()
                    planet_lvl = temp_planets[i].get_planet_lvl()
                    credit_per_hours = temp_planets[i].get_planet_credit_per_hour()
                    planet_type = temp_planets[i].get_planet_types()
                    planet_tier = temp_planets[i].get_planet_tier()
                    new_lvl = str((int(planet_lvl) + 1))

                    if planet_lvl == max_levels[i]:
                        cost_list.append(temp_planets[i].get_planet_cost())
                        increase_in_cap.append('99999')
                        increase_in_income.append('99999')

                        decider.append('99')
                    else:
                        cost_list.append(temp_planets[i].get_planet_cost())



                        increase_cap = int(planet_cap(new_lvl))- int(storage)
                        if increase_cap == 0:
                            increase_cap = 1
                        increase_in_cap.append(increase_cap)


                        new_credits_per_hour = credit_per_hour(planet_type,new_lvl,planet_tier)
                        increase_in_incomees = (str(int(new_credits_per_hour)-int(credit_per_hours)))
                        if increase_in_incomees == 0:
                            increase_in_incomees = 1
                        increase_in_income.append(increase_in_incomees)


                        decider.append(str((int(cost_list[i])/int(increase_in_cap[i])/ int(increase_in_income[i]))))


                value = min(decider)
                first = ''
                for index,item in enumerate(decider):
                    if item == value:
                        if first == '':
                            await channel.send(('planet',(index +1), '--->', (int(temp_planets[index].get_planet_lvl())+1)))
                            temp_planets[index].set_planet_lvl(str(int(temp_planets[index].get_planet_lvl())+1))
                            temp_planets[index].set_planet_cost(str(planet_cost(str(temp_planets[index].get_planet_lvl()))))
                            temp_planets[index].set_planet_storage(str(planet_cost(str(temp_planets[index].get_planet_lvl()))))
                            temp_planets[index].set_planet_credit_per_hour(str(credit_per_hour(temp_planets[index].get_planet_types(),temp_planets[index].get_planet_lvl(),temp_planets[index].get_planet_tier())))
                            current_storage += int(temp_planets[index].get_planet_storage())
                            first = '1'
                cost_list = []
                increase_in_cap = []
                increase_in_income = []
                decider = []
                await channel.send('Your storage went up to: {} '.format(current_storage))
            await channel.send('Your final storage is: {}'.format(current_storage))

            for index,item in enumerate(planet_list):
                await channel.send(('{} planet whent from lvl'.format(index+1),orig_planet_lvl[index], 'to lvl',temp_planets[index].get_planet_lvl()))
        except (Exception, ValueError) as e:
            print(str(e))




client.run(TOKEN)

它等待用户输入,如果您输入错误,它将完全中断,我尝试使用try和except块,但它也无法识别它(我可能使用错误)。如果有人有解决方案那就太好了!

1 个答案:

答案 0 :(得分:0)

您的代码太乱了,无法理解您想做什么。我建议您先清理代码,然后重写问题。以下是您的代码存在的问题。

1

使用check代替get_input_of_type()。也许get_input_of_type()工作正常,但是已经存在一个检查用户消息输入的功能。您的代码似乎使用了很多次,因此最好为较短的代码定义一个函数。

def is_number(msg):
    return msg.content.isdigit()

@client.event
async def on_message(message):
    if "hadescalc.planet()" == message.content.lower():
        await client.send_message("What is the first number?")
        firstnumber = await client.wait_for_message(
            author=message.author,
            channel=message.channel,
            check=is_number)
        firstnumber += 3
        await client.send_message("What is the second number?")
        secondnumber = await client.wait_for_message(
            author=message.author,
            channel=message.channel,
            check=is_number)
        await client.send_message("{} + {} = {}".format(
            firstnumber, secondnumber, firstnumber+secondnumber))

2

不要在函数中定义class。最好在Planet中定义on_message。并且使用set_***get_***代替@property@setter

class Planet:
    def __init__(self, level, ___):
        self._level = level
        # blah
        pass

    @property
    def level(self):
        return self._level

    @level.setter
    def level(self, new_level):
        self._level = new_level

3

您多次投放intstr,但这并不好。例如,**_lvl的值都是int,不需要强制转换str。删除所有不必要的类型转换。另外,我无法理解decider的功能,但是它可能无法如您所愿。 deciderlist中的str(实际上是所有int),因此min(decider)查找字母最小值而不是数字最小值。如果将**_lvl更改为int类型,它将返回预期的数字最小值。