[PYTHON] What to do if you get an error when trying to send a message in tasks.loop () immediately after startup

Recently, Misty has begun to get sick that she doesn't want to go to school. In Previous article, I was printing () the current time and scheduled transmission time for debugging, but I came up with the idea of "print on syslog (print () ) Send everything to Discord. ”I changed it, but an error occurred and I was struggling for about two days. I would like to introduce the coping method at that time.

Main subject

Code when throwing an error

bot.py


@tasks.loop(seconds=60)
async def loop():
    global time_set
    global tem_set

    w_list = ["Moon", "fire", "water", "wood", "Money", "soil", "Day"]  #It has evolved!
    now_t, now_dt = datetime.now().strftime('%H:%M'), w_list[datetime.now().weekday()]

    ch = client.get_channel(771155766056452167)
    await ch.send(f"Current time:`{now_t}`/ Today's day of the week:`{now_dt}`/ Scheduled transmission time:`{time_set}`/ Scheduled body temperature to be transmitted:`{tem_set}`")

    if now_dt != "Day":  # Day曜Day以外だったら送信するようにした
        if now_t == time_set:  #Is it the scheduled transmission time?
            dt_now = datetime.now().strftime("%Y-%m-%d")  #Current time 2020-01-Obtained in the form of 01, dt_Store in now

            file_name = "cfg.json"
            with open(file_name, "r", encoding="utf-8")as f:
                cfg = json.load(f)
                cfg["output"]["ans_1"] = f"{dt_now}"
                cfg["output"]["ans_4"] = f"{tem_set}"

                params = {"entry.{}".format(cfg["entry"][k]): cfg["output"][k] for k in cfg["entry"].keys()}
                res = requests.get(cfg["form_url"] + "formResponse", params=params)

            if res.status_code == 200:
                await template_embed(message=768274673984208926, title="Log information", description=f"[URL]({res.url})",
                                     name_1="Completion status", name_2="Sent body temperature", value_1="Succeeded", color=discord.Color.green())
            else:
                res.raise_for_status()
                await template_embed(message=768274673984208926, title="Log information", name_1="Completion status", name_2="Body temperature to be sent",
                                     value_1="An error has occurred.", color=discord.Color.red())

        else:
            if now_t == "21:00":
                time_set = setting_time_set()
                tem_set = set_tem()
                await template_embed(message=768274673984208926, title="Notification of transmission time update", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
                                     value_1=time_set, color=discord.Color.blue())

When I actually run this code, I get the following error: At first, I thought it was a copy / paste of the ID, but even if I copied it again, I got an error, so maybe there is something else? When I looked it up, [it was](https://qiita.com/coolwind0202/items/a4405be45734bd7f6cd5#attributeerror-%E5%9E%8B%E5%90%8D-object-has-no-attribute-% E5% B1% 9E% E6% 80% A7% E5% 90% 8D)!

Functions such as client.get_channel () return None until the BOT is ready. For example, did you suddenly get_channel () at the beginning of the program? To avoid this, you need to get it "after" the ready event occurs.

"Well, by the way ..." (crying) Where did my two days go?

error


AttributeError: 'NoType' object has no attribute 'send'

approach

The workaround was surprisingly easy, yes. Before doing get_channel () in the previous article, wait_until_ready () [(reference)](https://discordpy.readthedocs.io/ja/latest/api.html?highlight=wait_until_ready#discord.Client All you have to do is put in .wait_until_ready).

bot.py


@tasks.loop(seconds=60)
async def loop():
    global time_set
    global tem_set

    w_list = ["Moon", "fire", "water", "wood", "Money", "soil", "Day"]  #It has evolved!
    now_t, now_dt = datetime.now().strftime('%H:%M'), w_list[datetime.now().weekday()]

    await client.wait_until_ready()
    ch = client.get_channel(771155766056452167)
    await ch.send(f"Current time:`{now_t}`/ Today's day of the week:`{now_dt}`/ Scheduled transmission time:`{time_set}`/ Scheduled body temperature to be transmitted:`{tem_set}`")

    if now_dt != "Day":  # Day曜Day以外だったら送信するようにした
        if now_t == time_set:  #Is it the scheduled transmission time?
            dt_now = datetime.now().strftime("%Y-%m-%d")  #Current time 2020-01-Obtained in the form of 01, dt_Store in now

            file_name = "cfg.json"
            with open(file_name, "r", encoding="utf-8")as f:
                cfg = json.load(f)
                cfg["output"]["ans_1"] = f"{dt_now}"
                cfg["output"]["ans_4"] = f"{tem_set}"

                params = {"entry.{}".format(cfg["entry"][k]): cfg["output"][k] for k in cfg["entry"].keys()}
                res = requests.get(cfg["form_url"] + "formResponse", params=params)

            if res.status_code == 200:
                await template_embed(message=768274673984208926, title="Log information", description=f"[URL]({res.url})",
                                     name_1="Completion status", name_2="Sent body temperature", value_1="Succeeded", color=discord.Color.green())
            else:
                res.raise_for_status()
                await template_embed(message=768274673984208926, title="Log information", name_1="Completion status", name_2="Body temperature to be sent",
                                     value_1="An error has occurred.", color=discord.Color.red())

        else:
            if now_t == "21:00":
                time_set = setting_time_set()
                tem_set = set_tem()
                await template_embed(message=768274673984208926, title="Notification of transmission time update", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
                                     value_1=time_set, color=discord.Color.blue())

Oh, it's solved in one shot ()

Summary

--If you get an error when using a function such as get_channel () in tasks.loop, you can fix it by insertingwait_until_ready ().

I'm sorry for the very rough summary ... I hope it helps someone who is in a similar situation.

reference

-Check if Discord.py bot doesn't work

Recommended Posts

What to do if you get an error when trying to send a message in tasks.loop () immediately after startup
What to do if you get an error when trying to load mnist
What to do if you get a must override `get_config` error when trying to model.save in Keras
What to do if you get an error when importing matplotlib in Python (Mac)
What to do if you get an error when running "certbot renew" in CakePHP environment
What to do if you get an Undefined error when trying to use pip with pyenv
What to do if you get an error when installing Dlib (Ubuntu)
What to do if you get a "No versions found" error in pipenv
What to do if you get an error when installing python with pyenv
What to do if you get a Permission denied (public key) error when trying to pull on Github
What to do if you get an OpenSSL error when installing Python 2 with pyenv
What to do if you get a memory error when converting from PySparkDataFrame to PandasDataFrame
What to do if you get an Import Error when importing matplotlib with Jupyter
What to do if you get a minus zero in Python
What to do if you get a Cannot retrieve metalink for repository error in yum
What to do if you get the error RuntimeError: Python is not installed as a framework when trying to use matplitlib and pylab in Python 3.3
What to do if you get an error saying c compiler cannot create executables in configure
Workaround if you get an error when trying to install PySide with pip
[Python] What to check when you get a Unicode Decode Error in Django
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
What to do if you get an "unknown service" error from your gRPC server
What to do if you get "(35,'SSL connect error')" in pycurl (one of them)
What to do if you get "coverage unknown" in Coveralls
What to do if a 0xC0000005 error occurs in tf.train.start_queue_runners ()
What to do if you get the error ʻERR_FEATURE_UNAVAILABLE_ON_PLATFORM` when using ts-node-dev on Linux
What to do if you run python in IntelliJ and end with an error
What to do if you get a Call with too many input arguments error at DoAndReturn in a golang test
What to do when you get an error saying "Name resolution temporarily failed" on linux
What to do if you get Swagger-codegen in python and Import Error: No module named
What to do if you get a UnicodeDecodeError with pip install
What to do if you get an error when vagrant up when you enable public_network or private_network on Vagrant + Arch Linux → Install netctl
What to do if you get angry with'vertices' must be a 2D list ... in matplotlib arrow
What to do if pip --user returns an error in a virtual environment created with pyenv
What to do if you couldn't send an email to Yahoo with Python.
What to do if you get lost in file reference with FileNotFoundError
What to do if you get angry in TensorFlow v2 without attribute'app'
What to do if an error occurs when importing numpy with VScode
What to do if you get a TypeError with numpy min, max
[OSX] [pyenv] What to do when an SSL error occurs in pip
What to do when a warning message is displayed in pip list
What to do if an error message "There was a problem displaying this web page" is displayed in Chrome's Web Driver (Selenium)
What to do if you get `locale.Error: unsupported locale setting` when getting the day of the week from a date in Python
What to do if you get an error like'Qstring' has already been set to version 1 using mne python
What to do if you get a "Wrong Python Platform" warning when using Python with the NetBeans IDE
What to do if you get angry with "Value Error: unknown local: UTF-8" in python manage.py syncdb
What to do if a symbolic link error occurs in import cv while trying to install OpenCV in Python
[Python] What to do if an error occurs in pip (pyinstaller, pyautogui, etc.)
[python] What to do when an error occurs in send_keys of headless chrome
What to do if a Unicode Encode Error occurs in Sublime Text Python
What to do if you get "Python not configured." Using PyDev in Eclipse
If you get a long error when tabbing an interactive shell with Anaconda
What to do if a version error occurs in the selenium Chrome driver
What to do if a UnicodeDecodeError occurs in pip
What to do if you are told "Import Error: cannot import name'HTTPSHandler'" when building a virtual environment using virtualenv
What to do if an error occurs when loading a python project created with poetry into VS Code
When you get an error in python scraping (requests)
What to do if you get the error Input contains NaN, infinity or a value too large for dtype ('float64'). In machine learning
What to do if you get `No kernel for language python found` in Hydrogen
What to do if the print command itself causes an error in Maya python
What to do if you get the error "Error: opencv3: Does not support building both Python 2 and 3 wrappers" when installing openCV 3
What to do if pip gives a DistributionError in Homebrew