0

I’m trying to make a discord bot that will publish my public IP address on a command. Almost everything is working, but the IP address returns a NoneType. I have been using a library called publicip to get the IP address.

import discord
import publicip

client = discord.Client()

@client.event
async def on_ready():

    print(publicip.get())

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$ip?'):
        ip = str(publicip.get())
        await message.channel.send("The server ip is " + ip)

client.run('')
rfkortekaas
  • 6,049
  • 2
  • 27
  • 34
Dylan Bruns
  • 1
  • 1
  • 1

3 Answers3

1

just do

import requests

ip = requests.get('https://ipinfo.io/ip').text
Hyperx837
  • 773
  • 5
  • 13
0

You can capture the value of publicip.get() from stdout like this:

from io import StringIO
from contextlib import redirect_stdout

with StringIO() as buffer, redirect_stdout(buffer):
    publicip.get()
    ip = buffer.getvalue().split()[0]

print(ip) # prints your public IP

gives ip as your public IP (output from library to stdout captured in your variable).

Jarvis
  • 8,494
  • 3
  • 27
  • 58
0

The function publicip.get() returns None - always. It merely prints the client's public IP address. That is why your code sends None and not the IP address as one would expect.

Worse, when it fails to determine the IP address of the client it calls exit() which will nastily terminate your process. In that case an error message should be printed, but you are left with an aborted process.

I would strongly advise against using this package due to the fact that it does not return the IP address and that it will terminate your process if it fails to obtain one.

You can use the same service to get the IP address yourself:

import requests

def get_publicip():
    r = requests.get('https://ipinfo.io/json')
    return r.json()['ip']

Just add some error handling and your done.

Alternative services exist such as http://ipify.org/.

r = requests.get('http://api.ipify.org')
print(r.text)

There are other methods described in this question Getting a machine's external IP address with Python

mhawke
  • 84,695
  • 9
  • 117
  • 138