47132


Discordの発言を監視し、 `/tenki [都道府県]`
というコマンドを受け付けて天気予報を投稿するbotを作成したが、下記のようなエラーが発生した。

Error:

[code]

      File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site- packages\requests\models.py", line 892, in json
    return complexjson.loads(self.text, **kwargs)
      File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
      File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File 
    "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\json\decoder.py", line 
    357, in raw_decode
        raise JSONDecodeError("Expecting value", s, err.value) from None
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    
[/code]

Code:

[code]

    import discord
    import json
    import requests
    
    f = open("tenki.json", encoding='utf-8_sig')
    tenki = json.load(f)
    f.close()
    
    client = discord.Client()
    
    @client.event
    async def on_ready():
        print('Logged in as')
        print(client.user.name)
        print(client.user.id)
        print('------')
    
    @client.event
    async def on_message(message):     
        if message.content.startswith('/tenki'):
            url = 'http://weather.livedoor.com/forecast/webservice/json/v1'
            payload = {'city': ["tenki"]}
            data = requests.get(url, params = payload).json()
            await client.send_message(message.channel, data['title'])                
            await client.send_message(message.channel, data["link"])
    
    client.run(token)
    
[/code]

json code:

[code]

    {"道北": "011000","沖縄県": "471010"}
    
[/code]


CC BY-SA 4.0
2018-07-30T15:24:37.123
47107
2018-08-23T04:02:03.647
2018-08-23T04:02:03.647
29826
29457
question
python python3 json discord
DiscordにPythonで天気予報を流したい


metropolisさんのコメントのように、`["tenki"]`という文字列をパラメータで送るとJSONDecodeErrorが返ります。

パラメータを`payload = {'city': '011000'}`または`payload = {'city':
tenki['道北']}`に変更すると正常なXMLが戻ります。  
`on_message`関数を下記のように書き換えてみてはいかがでしょうか。

[code]

    if message.content.startswith('/tenki '):
        url = 'http://weather.livedoor.com/forecast/webservice/json/v1'
        place_name = message.content.lstrip('/tenki ').strip()
        if place_name in tenki:
            payload = {'city': tenki[place_name]}
            data = requests.get(url, params = payload).json()
            await client.send_message(message.channel, data['title'])
            await client.send_message(message.channel, data["link"])
        else:
            # 存在しない地名入力時のエラー処理
            await client.send_message(message.channel, '"{}"は未登録の地名です。'.format(place_name))
    
[/code]


CC BY-SA 4.0
2018-07-31T10:53:53.713
47132
2018-08-04T10:22:16.223
2018-08-04T10:22:16.223
9820
9820
47107
answer