Змея / Говнокод #28279 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
'''
Main file of bot
Главный фаил бота
'''
from discord.ext import commands

import wotb_api
import settings
import messages as m
from messages_gen import pars
from settings import bot_settings


class App():
    '''
    Main class of bot
    Главный класс бота
    '''
    def __init__(self):
        self.pars = pars()
        self.msg = m.msg()
        self.api = wotb_api.API()
        self.bot = commands.Bot(command_prefix=
                                bot_settings['command_prefix'])
        self.__token__ = settings.bot_settings['TOKEN']

    def error_handler(self,data):
        '''
        Сопостовляем полученную ошибку со словарём
        и возвращаем True если данные совпадают
        со словарём ошибок.
        '''
        for i in self.api.error_list:
            if data == i:
                return True
        return False

    def main(self):
        '''
        Здесь описанна логика бота, и его взаимодействие
        с другими модулями
        '''
        @self.bot.command()
        async def stats(ctx):
            command = ctx.message.content
            command = command.split(' ')
            print(f'Запрос: {command}')

            if len(command) == 2:
                player_data = self.api.get_player_stats(command[1])
                if self.error_handler(player_data):
                    await ctx.send(embed = self.
                                   msg.return_error_emb(player_data))
                else:
                    embed = self.pars.get_data(player_data,
                                               self.api.last_id)
                    await ctx.send(embed = embed)

            elif len(command) == 3:
                player_data = self.api.get_player_stats(command[1],
                                                        command[2])
                if self.error_handler(player_data):
                    await ctx.send(embed = self.
                                   msg.return_error_emb(player_data))
                else:
                    embed = self.pars.get_data(player_data,
                                               self.api.last_id)
                    await ctx.send(embed = embed)

            elif len(command) > 3:
                await ctx.send(embed = self.msg.return_error_emb('CFE'))
            else:
                await ctx.send(embed = self.msg.return_error_emb('NN'))

        @self.bot.command()
        async def ver(ctx):
            await ctx.send(embed = self.msg.about_embed())

        @self.bot.command()
        async def server(ctx):
            command = ctx.message.content
            command = command.split(' ')

            if len(command) == 2:
                if command[1].lower() == 'all':
                    s_status = ''
                    s_status = self.api.get_server_status('all')
                    if self.error_handler(s_status):
                        embed = ''
                        embed = self.msg.return_error_emb(s_status)
                        await ctx.send(embed = embed)
                    else:
                        embed = ''
                        embed = self.pars.server_status_all(s_status)
                        await ctx.send(embed = embed)

Как вам код в плане читаемости. Pylint дал мне 9.78/10 балов (это не полный код)

Non_type_object Non_type_object, (Updated )

Комментарии (12, +12)

Змея / Говнокод #28188 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
try:
    self._api = caller(self.url)
except ValueError as e:
    logging.error(f"Не удалось инициализировать класс API: ({str(e)})")
    raise ValueError(str(e))

hvx hvx, (Updated )

Комментарии (43, +43)

Змея / Говнокод #28164 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
import asyncio

async def hello():
    return "hello"

async def world():
    return "world"

async def comma():
    return ","

async def space():
    return " "

async def excl():
    return "!"

async def capitalize(coro):
    return (await coro).capitalize()

async def main():
    print(''.join(await asyncio.gather(*[asyncio.create_task(task) for task in (capitalize(hello()), comma(), space(), capitalize(world()), excl())])))

asyncio.run(main())

Изучаем asyncio через говнокод

valo94 valo94, (Updated )

Комментарии (29, +29)

Змея / Говнокод #28112 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
> cat antilol.py
#!/usr/bin/env python

import evdev

device = evdev.InputDevice('/dev/input/event2')

three = [0, 0, 0]

for event in device.read_loop():
    if event.type == evdev.ecodes.EV_KEY and event.value == 1:
        # print(event.code, evdev.ecodes.KEY[event.code])
        three = three[1:] + [event.code]
        if three == [
                        evdev.ecodes.KEY_L,
                        evdev.ecodes.KEY_O,
                        evdev.ecodes.KEY_L
                    ] or three == [
                        evdev.ecodes.KEY_K,
                        evdev.ecodes.KEY_J,
                        evdev.ecodes.KEY_K
                    ]:
            for i in range(0, 3):
                device.write(evdev.ecodes.EV_KEY, evdev.ecodes.KEY_BACKSPACE, 1)
                device.write(evdev.ecodes.EV_KEY, evdev.ecodes.KEY_BACKSPACE, 0)

Отучаемся от вредных привычек.

vistefan vistefan, (Updated )

Комментарии (100, +100)

Змея / Говнокод #28104 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
def _generate_greeting(self) -> str:
    date = datetime.datetime.fromtimestamp(time.time(), pytz.timezone(config.TIMEZONE))
    if 6 <= date.hour < 11:
        return 'Доброе утро!'
    elif 11 <= date.hour < 18:
        return 'Добрый день.'
    elif 18 <= date.hour < 23:
        return 'Добрый вечер.'
    else:
        return 'Доброй ночи.'

ISO ISO, (Updated )

Комментарии (19, +19)

Змея / Говнокод #28090 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
def getMyIPAddress():
    global __ip__
    if __ip__:
        return __ip__
    with suppress(Exception):
        __ip__ = get('https://api.my-ip.io/ip', timeout=.1).text
    with suppress(Exception):
        __ip__ = get('https://ipwhois.app/json/', timeout=.1).json()["ip"]
    with suppress(Exception):
        __ip__ = get('https://ipinfo.io/json', timeout=.1).json()["ip"]
    with suppress(Exception):
        __ip__ = ProxyTools.Patterns.IP.search(get('http://checkip.dyndns.org/', timeout=.1).text)
    with suppress(Exception):
        __ip__ = ProxyTools.Patterns.IP.search(get('https://spaceiran.com/myip/', timeout=.1).text)
    with suppress(Exception):
        __ip__ = get('https://ip.42.pl/raw', timeout=.1).text
    return getMyIPAddress()

Что имел в виду автор? Кто понял?

inho-pidar inho-pidar, (Updated )

Комментарии (24, +24)

Змея / Говнокод #28085 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
p = []
m = []

import telebot
import pyodbc
from telebot import apihelper
connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=(тут сервер);DATABASE=(наим базы);UID=(логин);PWD=(пароль)')

cursor = connection.cursor()
    
mySQLquery = ("""
                select  фамилия from OPCFIO)
                  """)
cursor.execute(mySQLquery)
results = cursor.fetchall()
i=0
    
for row in results:
    quality = row[0] #присваиваю имя
    id = row[1] #присваиваю фамилию
        
    p.append(id) #добавляю в массив
    m.append(quality) #добавляю в массив
    
    for j in range(len(p)):   
        bot = telebot.TeleBot('токен бота')
        apihelper.proxy = {
                       "http": "айпи прокси",
                        "https": "айпи прокси",
                        }
        @bot.message_handler()  
        def start(message):
            print(str(p[j]))
            if message.text == str(p[j]):
                    bot.send_message(message.chat.id, 'Вы выбрали имя '+ str(quality[j])  +"   " + "Фамилия будет" + str(m[j]))
            else:
                    bot.send_message(message.chat.id, 'Такого имени нету {}'.format(message.text))

bot.polling()

Что я такого сделал, что я должен был это увидеть...

Vindicar Vindicar, (Updated )

Комментарии (16, +16)

Змея / Говнокод #28074 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
# оутпут и инпут
            "print": self.hprint,     # вывод в консоль
            "println": self.hprintln, # вывод в консоль с переносом строки
            "input": self.hinput,     # ввод с консоли
            "inputln": self.hinputln, # ввод с консоли с новой строки

питонисты бушуют

kcalbCube kcalbCube, (Updated )

Комментарии (10, +10)

Змея / Говнокод #28069 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
import docx
doc = docx.Document('F://PythonProjects//Trash//example.docx')
paras = doc.paragraphs

name = input()

for para in paras:
    para = para.text.split(' ')
    for word in para:
        //'NAME,' - строка в исходном файле
        if word == 'NAME,':
            word = name + ','
    para = ' '.join(para)

Вуду-программирование. "Если я присвою переменной ссылку на объект, а потом присвою её же другую ссылку, то первый объект должен замениться на второй по всей программе."

Vindicar Vindicar, (Updated )

Комментарии (7, +7)